<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getUserExperimentGroupsApi } from '#/api/core/experiment';
import type { ExperimentApi } from '#/api/core/experiment';
import { Page } from '@vben/common-ui';
import { Button, Card, Input, Space, Tag, message } from 'ant-design-vue';
import { ref } from 'vue';

const userId = ref('');
const userGroupLoading = ref(false);
const userGroups = ref<ExperimentApi.UserExperimentGroupItem[]>([]);

const gridOptions: VxeGridProps<ExperimentApi.UserExperimentGroupItem> = {
  columns: [
    { field: 'experiment_id', title: '实验ID', width: 100 },
    { field: 'experiment_name', title: '实验名称', minWidth: 180 },
    { field: 'variant_id', title: '变体ID', width: 100 },
    { field: 'variant_name', title: '变体名称', minWidth: 180 },
    {
      field: 'params',
      formatter: ({ cellValue }) => (cellValue ? JSON.stringify(cellValue) : '-'),
      title: '变体参数',
      minWidth: 280,
    },
  ],
  data: userGroups.value,
  height: 'auto',
  pagerConfig: {
    enabled: false,
  },
  rowConfig: {
    isHover: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({ gridOptions });

async function searchUserGroups() {
  const currentUserId = userId.value.trim();
  if (!currentUserId) {
    message.warning('请输入玩家 UID');
    return;
  }

  userGroupLoading.value = true;
  try {
    const response = await getUserExperimentGroupsApi(currentUserId);
    userGroups.value = Array.isArray(response) ? response : [];
    GridApi.setGridOptions({
      data: userGroups.value,
    });
    if (userGroups.value.length === 0) {
      message.info('该玩家暂无实验分组记录');
    }
  } finally {
    userGroupLoading.value = false;
  }
}
</script>

<template>
  <Page auto-content-height>
    <Card title="玩家实验分组查询">
      <Space>
        <Input v-model:value="userId" placeholder="请输入玩家 UID" style="width: 280px" />
        <Button type="primary" :loading="userGroupLoading" @click="searchUserGroups">
          查询参与实验体
        </Button>
      </Space>

      <div class="mt-4">
        <Tag color="blue">支持查询玩家当前参与的所有实验及命中的变体</Tag>
      </div>

      <div class="mt-4">
        <Grid />
      </div>
    </Card>
  </Page>
</template>