<script setup lang="ts">
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteExperimentApi,
  getExperimentResultApi,
  getExperimentListApi,
} from '#/api/core/experiment';
import type { ExperimentApi } from '#/api/core/experiment';
import { Page, useVbenModal } from '@vben/common-ui';
import dayjs from 'dayjs';
import { Button, Card, Modal, Space, Table, Tag, message } from 'ant-design-vue';
import { onActivated, ref } from 'vue';

import ExperimentFormModal from './experiment-form-modal.vue';

const statusOptions = [
  { label: '全部', value: -1 },
  { label: '草稿', value: 0 },
  { label: '运行中', value: 1 },
  { label: '已暂停', value: 2 },
  { label: '已结束', value: 3 },
];

function formatTime(value: null | string) {
  if (!value) {
    return '-';
  }
  return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
}

function getStatusText(status: number) {
  return (
    statusOptions.find((item) => item.value === status)?.label ||
    `未知状态(${status})`
  );
}

function getStatusColor(status: number) {
  switch (status) {
    case 0:
      return 'default';
    case 1:
      return 'green';
    case 2:
      return 'orange';
    case 3:
      return 'red';
    default:
      return 'blue';
  }
}

const formOptions: VbenFormProps = {
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入实验名称',
      },
      fieldName: 'keyword',
      label: '实验名称',
    },
    {
      component: 'Select',
      componentProps: {
        options: statusOptions,
      },
      defaultValue: -1,
      fieldName: 'status',
      label: '状态',
    },
  ],
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  submitOnChange: false,
  submitOnEnter: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-2',
};

const gridOptions: VxeGridProps<ExperimentApi.ExperimentItem> = {
  columns: [
    { field: 'id', title: 'ID', width: 80 },
    { field: 'name', title: '实验名称', minWidth: 180 },
    { field: 'description', title: '实验描述', minWidth: 220 },
    {
      field: 'status',
      title: '状态',
      slots: { default: 'status' },
      width: 120,
    },
    {
      field: 'start_time',
      formatter: ({ cellValue }) => formatTime(cellValue),
      title: '开始时间',
      width: 180,
    },
    {
      field: 'end_time',
      formatter: ({ cellValue }) => formatTime(cellValue),
      title: '结束时间',
      width: 180,
    },
    {
      field: 'updated_at',
      formatter: ({ cellValue }) => formatTime(cellValue),
      title: '更新时间',
      width: 180,
    },
    {
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 220,
    },
  ],
  height: 'auto',
  pagerConfig: {},
  proxyConfig: {
    response: {
      result: 'list',
      total: 'total',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        const response = await getExperimentListApi({
          page: page.currentPage,
          page_size: page.pageSize,
          status: formValues.status === -1 ? undefined : formValues.status,
        });

        if (!formValues.keyword) {
          return {
          ...response,
        };
        }

        const keyword = String(formValues.keyword).trim().toLowerCase();
        const list = response.list.filter((item) =>
          [item.name, item.description]
            .filter(Boolean)
            .some((field) => String(field).toLowerCase().includes(keyword)),
        );

        return {
          ...response,
          list,
          total: list.length,
        };
      },
    },
  },
  rowConfig: {
    isHover: true,
  },
};

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

onActivated(async () => {
  await GridApi.query();
});

const [ExperimentModal, experimentModalApi] = useVbenModal({
  connectedComponent: ExperimentFormModal,
  onClosed: async () => {
    experimentModalApi.close();
    await GridApi.query();
  },
});

const resultModalOpen = ref(false);
const resultLoading = ref(false);
const resultData = ref<ExperimentApi.ExperimentResult | null>(null);

const resultColumns = [
  { dataIndex: 'variant_id', key: 'variant_id', title: '变体ID', width: 100 },
  { dataIndex: 'variant_name', key: 'variant_name', title: '变体名称' },
  { dataIndex: 'exposure_count', key: 'exposure_count', title: '曝光数' },
  { dataIndex: 'convert_count', key: 'convert_count', title: '转化数' },
  {
    dataIndex: 'convert_rate',
    key: 'convert_rate',
    title: '转化率',
    customRender: ({ text }: { text: number }) => `${(Number(text) * 100).toFixed(2)}%`,
  },
  {
    dataIndex: 'total_value',
    key: 'total_value',
    title: '总价值',
    customRender: ({ text }: { text: number }) => Number(text).toFixed(2),
  },
  { dataIndex: 'user_count', key: 'user_count', title: '用户数' },
];

function openCreateModal() {
  experimentModalApi.setData({ mode: 'create' });
  experimentModalApi.open();
}

function openEditModal(record: ExperimentApi.ExperimentItem) {
  experimentModalApi.setData({ mode: 'edit', record });
  experimentModalApi.open();
}

function handleDelete(record: ExperimentApi.ExperimentItem) {
  Modal.confirm({
    content: `确认删除实验“${record.name}”吗？`,
    title: '删除确认',
    async onOk() {
      await deleteExperimentApi(record.id);
      message.success('实验删除成功');
      await GridApi.query();
    },
  });
}

async function showResult(record: ExperimentApi.ExperimentItem) {
  resultLoading.value = true;
  resultModalOpen.value = true;
  try {
    resultData.value = await getExperimentResultApi(record.id);
  } finally {
    resultLoading.value = false;
  }
}
</script>

<template>
  <Page auto-content-height>
    <ExperimentModal class="w-[60%]" />
    <Card class="mb-5" title="AB 实验管理">
      <Space>
        <Button type="primary" @click="openCreateModal">新增实验</Button>
      </Space>
    </Card>
    <Grid>
      <template #status="{ row }">
        <Tag :color="getStatusColor(row.status)">
          {{ getStatusText(row.status) }}
        </Tag>
      </template>
      <template #operation="{ row }">
        <Space>
          <Button size="small" @click="showResult(row)">结果</Button>
          <Button size="small" type="primary" @click="openEditModal(row)">编辑</Button>
          <Button danger size="small" @click="handleDelete(row)">删除</Button>
        </Space>
      </template>
    </Grid>
    <Modal
      v-model:open="resultModalOpen"
      :footer="null"
      :title="resultData ? `${resultData.experiment_name} - 实验结果` : '实验结果'"
      width="960px"
    >
      <div class="mb-4" v-if="resultData">
        <Space>
          <span>实验ID：{{ resultData.experiment_id }}</span>
          <Tag :color="getStatusColor(resultData.status)">
            {{ getStatusText(resultData.status) }}
          </Tag>
        </Space>
      </div>
      <Table
        :columns="resultColumns"
        :data-source="resultData?.variants || []"
        :loading="resultLoading"
        :pagination="false"
        :scroll="{ x: 820 }"
        row-key="variant_id"
        size="small"
      />
    </Modal>
  </Page>
</template>