<script lang="ts" setup>
/**
 * AI 生成记录列表页
 * 顶部用量摘要（随当前筛选刷新）+ VxeGrid 明细
 * 平台/模型筛选下拉：从 option 接口注入，选平台后联动刷新模型列表
 */
import { onMounted, reactive, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Card, Col, Row, Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import { getAiModelOption } from '../platform/api/model';
import { getAiPlatformOption } from '../platform/api';
import { getAiGenerationList, getAiGenerationUsageStats } from './api';
import DetailModal from './components/detail-modal.vue';
import { formOptions, normalizeAiGenerationFilters } from './config/search';
import { gridOptions } from './config/table';
import { formatDurationMs } from './utils/format';

defineOptions({ name: 'AiGeneration' });

const stats = reactive({
  total_tokens: 0,
  prompt_tokens: 0,
  completion_tokens: 0,
  avg_duration_ms: 0,
  success_rate: 0,
  total_count: 0,
  success_count: 0,
  fail_count: 0,
  // P4 质量指标：采纳率/直接采纳率/修改率/药名未匹配率/人均重生成
  adopted_count: 0,
  adoption_rate: 0,
  direct_rate: 0,
  modified_rate: 0,
  unmatched_rate: 0,
  avg_regen: 0,
});

/** 全量模型 option，选平台时按 platform_id 过滤 */
const allModelOptions = ref<Array<{ label: string; value: string; platform_id?: number }>>([]);

/** 把毫秒格式化为秒文案 */
function formatDuration(ms: number) {
  return formatDurationMs(ms);
}

/** 按当前搜索表单刷新摘要卡片 */
async function refreshStats(formValues?: Record<string, any>) {
  const params = normalizeAiGenerationFilters(formValues || {});
  try {
    const res = await getAiGenerationUsageStats(params);
    const data = res?.data || res || {};
    stats.total_tokens = Number(data.total_tokens || 0);
    stats.prompt_tokens = Number(data.prompt_tokens || 0);
    stats.completion_tokens = Number(data.completion_tokens || 0);
    stats.avg_duration_ms = Number(data.avg_duration_ms || 0);
    stats.success_rate = Number(data.success_rate || 0);
    stats.total_count = Number(data.total_count || 0);
    stats.success_count = Number(data.success_count || 0);
    stats.fail_count = Number(data.fail_count || 0);
    stats.adopted_count = Number(data.adopted_count || 0);
    stats.adoption_rate = Number(data.adoption_rate || 0);
    stats.direct_rate = Number(data.direct_rate || 0);
    stats.modified_rate = Number(data.modified_rate || 0);
    stats.unmatched_rate = Number(data.unmatched_rate || 0);
    stats.avg_regen = Number(data.avg_regen || 0);
  } catch {
    // 摘要失败不阻断列表
  }
}

/** 按平台刷新模型下拉；清空平台时恢复全部模型 */
function refreshModelSchema(platformId?: number) {
  const filtered =
    platformId && platformId > 0
      ? allModelOptions.value.filter((m) => Number(m.platform_id) === platformId)
      : allModelOptions.value;
  gridApi.formApi?.updateSchema?.([
    {
      fieldName: 'model',
      componentProps: {
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
        options: filtered,
        placeholder: '全部模型',
      },
    },
  ]);
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    ...formOptions,
    schema: formOptions.schema?.map((item) =>
      item.fieldName === 'platform_id'
        ? {
            ...item,
            componentProps: {
              ...item.componentProps,
              onChange: (val: number | undefined) => {
                // 切换平台时清掉已选模型，避免跨平台残留
                gridApi.formApi?.setFieldValue?.('model', undefined);
                refreshModelSchema(val ? Number(val) : undefined);
              },
            },
          }
        : item,
    ),
  },
  gridOptions: {
    ...gridOptions,
    proxyConfig: {
      ...gridOptions.proxyConfig,
      ajax: {
        query: async ({ page }, formValues) => {
          void refreshStats(formValues);
          return await getAiGenerationList({
            page: page.currentPage,
            pageSize: page.pageSize,
            ...normalizeAiGenerationFilters(formValues || {}),
          });
        },
      },
    },
  },
});

const [DetailModalComp, detailModalApi] = useVbenModal({
  connectedComponent: DetailModal,
});

function openDetail(row: any) {
  detailModalApi.setData({ id: Number(row?.id || 0) });
  detailModalApi.open();
}

function statusColor(status: number) {
  if (status === 1) return 'success';
  if (status === 2) return 'error';
  return 'processing';
}

onMounted(async () => {
  void refreshStats();
  try {
    const [platformRes, modelRes] = await Promise.all([
      getAiPlatformOption(),
      getAiModelOption(),
    ]);
    const platforms = Array.isArray(platformRes)
      ? platformRes
      : platformRes?.data || [];
    const models = Array.isArray(modelRes) ? modelRes : modelRes?.data || [];
    allModelOptions.value = models.map((m: any) => ({
      label: m.label || `${m.name || ''}（${m.code || m.value || ''}）`,
      value: String(m.value ?? m.code ?? ''),
      platform_id: Number(m.platform_id || 0),
    }));
    gridApi.formApi?.updateSchema?.([
      {
        fieldName: 'platform_id',
        componentProps: {
          allowClear: true,
          showSearch: true,
          optionFilterProp: 'label',
          options: platforms,
          placeholder: '全部平台',
          onChange: (val: number | undefined) => {
            gridApi.formApi?.setFieldValue?.('model', undefined);
            refreshModelSchema(val ? Number(val) : undefined);
          },
        },
      },
    ]);
    refreshModelSchema();
  } catch {
    // option 失败时下拉为空，仍可用关键词筛
  }
});
</script>

<template>
  <Page auto-content-height>
    <DetailModalComp />
    <div class="mb-3">
      <Row :gutter="12">
        <Col :xs="12" :sm="8" :md="4">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">总 Tokens</div>
            <div class="mt-1 text-lg font-semibold">{{ stats.total_tokens }}</div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="4">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">Prompt</div>
            <div class="mt-1 text-lg font-semibold">{{ stats.prompt_tokens }}</div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="4">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">Completion</div>
            <div class="mt-1 text-lg font-semibold">{{ stats.completion_tokens }}</div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="4">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">平均耗时</div>
            <div class="mt-1 text-lg font-semibold">
              {{ formatDuration(stats.avg_duration_ms) }}
            </div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="4">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">成功率</div>
            <div class="mt-1 text-lg font-semibold">{{ stats.success_rate }}%</div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="4">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">请求数</div>
            <div class="mt-1 text-lg font-semibold">
              {{ stats.success_count }}/{{ stats.total_count }}
              <span class="ml-1 text-xs font-normal text-[hsl(var(--muted-foreground))]">
                失败 {{ stats.fail_count }}
              </span>
            </div>
          </Card>
        </Col>
      </Row>
      <!-- P4 质量指标行：度量 AI 生成质量，随筛选联动（如按场景/时间对比） -->
      <Row :gutter="12" class="mt-3">
        <Col :xs="12" :sm="8" :md="5">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">
              采纳率
              <span class="ml-1 opacity-70">已采纳/成功数</span>
            </div>
            <div class="mt-1 text-lg font-semibold">
              {{ stats.adoption_rate }}%
              <span class="ml-1 text-xs font-normal text-[hsl(var(--muted-foreground))]">
                {{ stats.adopted_count }}/{{ stats.success_count }}
              </span>
            </div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="5">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">
              直接采纳率
              <span class="ml-1 opacity-70">未改原稿直接用</span>
            </div>
            <div class="mt-1 text-lg font-semibold text-[hsl(var(--primary))]">
              {{ stats.direct_rate }}%
            </div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="5">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">
              修改率
              <span class="ml-1 opacity-70">采纳但改过原稿</span>
            </div>
            <div class="mt-1 text-lg font-semibold">{{ stats.modified_rate }}%</div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="5">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">
              药名未匹配率
              <span class="ml-1 opacity-70">越低越好</span>
            </div>
            <div class="mt-1 text-lg font-semibold">{{ stats.unmatched_rate }}%</div>
          </Card>
        </Col>
        <Col :xs="12" :sm="8" :md="4">
          <Card size="small">
            <div class="text-xs text-[hsl(var(--muted-foreground))]">
              人均重生成
              <span class="ml-1 opacity-70">>1 需关注</span>
            </div>
            <div class="mt-1 text-lg font-semibold">{{ stats.avg_regen }}</div>
          </Card>
        </Col>
      </Row>
    </div>
    <Grid>
      <template #status="{ row }">
        <Tag :color="statusColor(Number(row.status))">
          {{ row.status_txt || row.status }}
        </Tag>
      </template>
      <template #tokens="{ row }">
        <span :title="`P ${row.prompt_tokens} / C ${row.completion_tokens}`">
          {{ row.total_tokens || 0 }}
        </span>
      </template>
      <template #duration="{ row }">
        {{ formatDuration(Number(row.duration_ms || 0)) }}
      </template>
      <template #adopted="{ row }">
        <!-- P4 采纳状态：直接采纳绿色（质量最好）、改后采纳蓝色、未采纳灰字 -->
        <Tag
          v-if="Number(row.is_adopted) === 1"
          :color="Number(row.is_modified_final) === 1 ? 'processing' : 'success'"
        >
          {{ row.adopted_txt }}
        </Tag>
        <span v-else class="text-xs text-[hsl(var(--muted-foreground))]">未采纳</span>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '详情',
              type: 'link',
              onClick: () => openDetail(row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
