<script lang="ts" setup>
import type { AppAgoraErrorLogItem } from '#/api/legacy/app-system';

import { computed, reactive, ref, watch } from 'vue';

import { Page } from '@vben/common-ui';
import { useAccessStore } from '@vben/stores';

import {
  Button,
  Card,
  DateRangePicker,
  Input,
  Modal,
  Pagination,
  Select,
  Space,
  Table,
  Tag,
} from 'antdv-next';

import { pageAgoraErrorLogs } from '#/api/legacy/app-system';
import SysOriginSelect from '#/components/sys-origin-select.vue';
import InlineFilterField from '#/views/_shared/inline-filter-field.vue';
import InlineFilterToolbar from '#/views/_shared/inline-filter-toolbar.vue';
import { formatDate, getAllowedSysOrigins } from '#/views/system/shared';

defineOptions({ name: 'AppSystemAgoraErrorLog' });

const categoryOptions = [{ label: '声网', value: 'AGORA' }];
const bannedOptions = [
  { label: '全部', value: '' },
  { label: '仅 BannedByServer', value: 'true' },
];

const columns = [
  { dataIndex: 'createTime', key: 'createTime', title: '上报时间', width: 170 },
  { dataIndex: 'userId', key: 'userId', title: '用户ID', width: 150 },
  { dataIndex: 'roomId', key: 'roomId', title: '房间ID', width: 150 },
  { dataIndex: 'agoraUid', key: 'agoraUid', title: 'Agora UID', width: 140 },
  { dataIndex: 'errorCodeType', key: 'errorCodeType', title: 'ErrorCodeType', width: 220 },
  {
    dataIndex: 'connectionChangedReasonType',
    key: 'connectionChangedReasonType',
    title: 'ConnectionChangedReasonType',
    width: 260,
  },
  { dataIndex: 'networkType', key: 'networkType', title: '网络', width: 110 },
  { dataIndex: 'flags', key: 'flags', title: '状态', width: 220 },
  { dataIndex: 'reqClient', key: 'reqClient', title: '客户端', width: 120 },
  { dataIndex: 'actions', fixed: 'right' as const, key: 'actions', title: '操作', width: 100 },
];

const accessStore = useAccessStore();
const sysOriginOptions = computed(() => {
  const options = getAllowedSysOrigins(accessStore.accessCodes || []);
  return options.length > 0 ? options : getAllowedSysOrigins([]);
});

const loading = ref(false);
const detailsOpen = ref(false);
const detailsText = ref('');
const list = ref<AppAgoraErrorLogItem[]>([]);
const total = ref(0);
const rangeDate = ref<[string, string] | null>(null);

const query = reactive<Record<string, any>>({
  agoraUid: '',
  bannedOnly: '',
  category: 'AGORA',
  cursor: 1,
  endTime: '',
  errorCodeType: '',
  limit: 20,
  networkType: '',
  reasonType: '',
  roomId: '',
  startTime: '',
  sysOrigin: '',
  userId: '',
});

watch(rangeDate, (value) => {
  query.startTime = value?.[0] || '';
  query.endTime = value?.[1] || '';
});

watch(
  sysOriginOptions,
  (options) => {
    if (!query.sysOrigin) {
      query.sysOrigin = String(options[0]?.value || '');
    }
  },
  { immediate: true },
);

watch(
  () => query.sysOrigin,
  (value) => {
    if (value) {
      void loadData(true);
    }
  },
  { immediate: true },
);

async function loadData(reset = false) {
  if (!query.sysOrigin) {
    return;
  }
  if (reset) {
    query.cursor = 1;
  }
  loading.value = true;
  try {
    const result = await pageAgoraErrorLogs({
      agoraUid: query.agoraUid,
      bannedOnly: query.bannedOnly,
      cursor: query.cursor,
      endTime: query.endTime,
      errorCodeType: query.errorCodeType,
      limit: query.limit,
      networkType: query.networkType,
      reasonType: query.reasonType,
      roomId: query.roomId,
      startTime: query.startTime,
      sysOrigin: query.sysOrigin,
      userId: query.userId,
    });
    list.value = result.records || [];
    total.value = Number(result.total || 0);
  } finally {
    loading.value = false;
  }
}

function handlePageChange(page: number, pageSize: number) {
  query.cursor = page;
  query.limit = pageSize;
  void loadData();
}

function showDetails(record: AppAgoraErrorLogItem) {
  const payload = record.rawPayload || '{}';
  try {
    detailsText.value = JSON.stringify(JSON.parse(payload), null, 2);
  } catch {
    detailsText.value = payload;
  }
  detailsOpen.value = true;
}

function tokenText(value: boolean | null | undefined) {
  if (value === true) {
    return 'Token成功';
  }
  if (value === false) {
    return 'Token失败';
  }
  return 'Token未知';
}

function tokenColor(value: boolean | null | undefined) {
  if (value === true) {
    return 'green';
  }
  if (value === false) {
    return 'red';
  }
  return 'default';
}
</script>

<template>
  <Page title="错误日志 - 声网">
    <Card>
      <InlineFilterToolbar class="toolbar">
        <InlineFilterField label="分类">
          <Select
            v-model:value="query.category"
            :options="categoryOptions"
            disabled
            style="width: 120px"
          />
        </InlineFilterField>
        <InlineFilterField label="系统">
          <SysOriginSelect
            v-model:value="query.sysOrigin"
            :options="sysOriginOptions"
            style="width: 140px"
          />
        </InlineFilterField>
        <InlineFilterField label="用户ID">
          <Input
            v-model:value="query.userId"
            allow-clear
            placeholder="用户ID"
            style="width: 160px"
          />
        </InlineFilterField>
        <InlineFilterField label="房间ID">
          <Input
            v-model:value="query.roomId"
            allow-clear
            placeholder="房间ID"
            style="width: 160px"
          />
        </InlineFilterField>
        <InlineFilterField label="Agora UID" :label-width="92">
          <Input
            v-model:value="query.agoraUid"
            allow-clear
            placeholder="Agora UID"
            style="width: 160px"
          />
        </InlineFilterField>
        <InlineFilterField label="ErrorCode" :label-width="92">
          <Input
            v-model:value="query.errorCodeType"
            allow-clear
            placeholder="ErrorCodeType"
            style="width: 180px"
          />
        </InlineFilterField>
        <InlineFilterField label="Reason" :label-width="76">
          <Input
            v-model:value="query.reasonType"
            allow-clear
            placeholder="ConnectionChangedReasonType"
            style="width: 220px"
          />
        </InlineFilterField>
        <InlineFilterField label="踢出规则" :label-width="84">
          <Select
            v-model:value="query.bannedOnly"
            :options="bannedOptions"
            style="width: 170px"
          />
        </InlineFilterField>
        <InlineFilterField label="网络">
          <Input
            v-model:value="query.networkType"
            allow-clear
            placeholder="wifi / mobile"
            style="width: 140px"
          />
        </InlineFilterField>
        <InlineFilterField label="时间范围" :control-width="360">
          <DateRangePicker
            v-model:value="rangeDate"
            show-time
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </InlineFilterField>
        <Button :loading="loading" type="primary" @click="loadData(true)">
          搜索
        </Button>
      </InlineFilterToolbar>

      <Table
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="false"
        row-key="id"
        :scroll="{ x: 1700 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>
          <template v-else-if="column.key === 'connectionChangedReasonType'">
            <Space wrap>
              <span>{{ record.connectionChangedReasonType || '-' }}</span>
              <Tag v-if="record.bannedByServer" color="red">
                BannedByServer
              </Tag>
            </Space>
          </template>
          <template v-else-if="column.key === 'flags'">
            <Space wrap>
              <Tag :color="record.isTimeout ? 'orange' : 'default'">
                {{ record.isTimeout ? 'Timeout' : '非Timeout' }}
              </Tag>
              <Tag :color="tokenColor(record.tokenRequestSuccess)">
                {{ tokenText(record.tokenRequestSuccess) }}
              </Tag>
            </Space>
          </template>
          <template v-else-if="column.key === 'actions'">
            <Button size="small" type="link" @click="showDetails(record)">
              详情
            </Button>
          </template>
        </template>
      </Table>

      <div class="pagination">
        <Pagination
          :current="query.cursor"
          :page-size="query.limit"
          :total="total"
          show-size-changer
          @change="handlePageChange"
          @showSizeChange="handlePageChange"
        />
      </div>
    </Card>

    <Modal
      :open="detailsOpen"
      destroy-on-close
      title="原始上报内容"
      width="760"
      @cancel="detailsOpen = false"
      @ok="detailsOpen = false"
    >
      <pre class="json-box">{{ detailsText }}</pre>
    </Modal>
  </Page>
</template>

<style scoped>
.toolbar {
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.json-box {
  background: #0f172a;
  border-radius: 8px;
  color: #e2e8f0;
  margin: 0;
  max-height: 60vh;
  overflow: auto;
  padding: 16px;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
