<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';

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

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

import {
  pageGmGoldOperation,
  reviewGmGoldOperation,
} from '#/api/legacy/gm';
import { getUserBaseInfoBySysOriginAccount } from '#/api/legacy/user';
import AccountInput from '#/components/account-input.vue';
import UserProfileLink from '#/views/operate/components/user-profile-link.vue';
import {
  formatDate,
  getDisplaySysOriginText,
} from '#/views/system/shared';

defineOptions({ name: 'GmGoldOperationReview' });

const loading = ref(false);
const reviewing = ref(false);
const list = ref<Array<Record<string, any>>>([]);
const total = ref(0);
const rangeDate = ref<[string, string] | null>(null);
const userSearch = ref('');

const query = reactive({
  applicantId: '',
  endTime: '',
  operationType: undefined as number | undefined,
  pageIndex: 1,
  pageSize: 20,
  startTime: '',
  status: 'PENDING',
  userId: '',
});

const columns = [
  { dataIndex: 'userProfile', key: 'userProfile', title: '用户', width: 240 },
  { dataIndex: 'sysOrigin', key: 'sysOrigin', title: '系统', width: 100 },
  { dataIndex: 'operationType', key: 'operationType', title: '类型', width: 100 },
  { dataIndex: 'quantity', key: 'quantity', title: '金币数量', width: 120 },
  { dataIndex: 'reasonName', key: 'reasonName', title: '原因', width: 120 },
  { dataIndex: 'remarks', key: 'remarks', title: '备注', width: 220 },
  { dataIndex: 'applicant', key: 'applicant', title: '申请人', width: 160 },
  { dataIndex: 'status', key: 'status', title: '状态', width: 110 },
  { dataIndex: 'reviewer', key: 'reviewer', title: '审核人', width: 160 },
  { dataIndex: 'time', key: 'time', title: '时间', width: 240 },
  { dataIndex: 'actions', key: 'actions', title: '操作', width: 160 },
];

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

function parseEncodedValue(value: unknown) {
  const raw = String(value ?? '');
  const match = raw.match(/^\*(.*)\*$/);
  if (!match) {
    return {
      accountType: '',
      content: raw,
      sysOrigin: '',
    };
  }
  const body = match[1] || '';
  return {
    accountType: body.match(/accountType:([^,]*)/)?.[1] || '',
    content: body.match(/content:(.*)$/)?.[1] || '',
    sysOrigin: body.match(/sysOrigin:([^,]*)/)?.[1] || '',
  };
}

async function resolveUserId() {
  const parsed = parseEncodedValue(userSearch.value);
  const content = String(parsed.content || '').trim();
  if (!content) {
    return '';
  }
  if (!parsed.accountType || parsed.accountType === 'LONG') {
    return content.replace(/[^\d]/g, '');
  }
  if (!parsed.sysOrigin) {
    message.warning('请选择系统');
    return '';
  }
  const result = await getUserBaseInfoBySysOriginAccount(parsed.sysOrigin, content);
  const userId = result?.id || result?.userId;
  if (!userId) {
    message.warning('未找到用户');
    return '';
  }
  return String(userId);
}

async function loadData(reset = false) {
  if (reset) {
    query.pageIndex = 1;
  }
  loading.value = true;
  try {
    query.userId = await resolveUserId();
    const result = await pageGmGoldOperation({
      ...query,
      applicantId: query.applicantId || undefined,
      operationType: query.operationType,
      userId: query.userId || undefined,
    });
    list.value = result.records || [];
    total.value = result.total || 0;
  } finally {
    loading.value = false;
  }
}

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

function statusColor(status?: string) {
  if (status === 'APPROVED') {
    return 'success';
  }
  if (status === 'REJECTED') {
    return 'error';
  }
  return 'warning';
}

function handleReview(record: Record<string, any>, approved: boolean) {
  Modal.confirm({
    title: approved ? '确认通过该金币操作？' : '确认拒绝该金币操作？',
    okText: approved ? '通过' : '拒绝',
    okType: approved ? 'primary' : 'danger',
    async onOk() {
      reviewing.value = true;
      try {
        await reviewGmGoldOperation({
          approved,
          id: record.id,
          reviewRemark: approved ? '同意' : '拒绝',
        });
        message.success(approved ? '已通过并执行金币操作' : '已拒绝');
        await loadData();
      } finally {
        reviewing.value = false;
      }
    },
  });
}

void loadData(true);
</script>

<template>
  <Page title="金币操作审核">
    <Card>
      <div class="toolbar">
        <Select
          v-model:value="query.status"
          allow-clear
          placeholder="状态"
          style="width: 140px"
          :options="[
            { label: '待审核', value: 'PENDING' },
            { label: '已通过', value: 'APPROVED' },
            { label: '已拒绝', value: 'REJECTED' },
          ]"
        />
        <Select
          v-model:value="query.operationType"
          allow-clear
          placeholder="操作类型"
          style="width: 140px"
          :options="[
            { label: '增加金币', value: 0 },
            { label: '扣除金币', value: 1 },
          ]"
        />
        <AccountInput
          v-model:value="userSearch"
          default-select-type="LONG"
          placeholder="用户ID"
          style="width: 260px"
        />
        <Input
          v-model:value="query.applicantId"
          allow-clear
          placeholder="申请人后台ID"
          style="width: 160px"
        />
        <DatePicker.RangePicker
          v-model:value="rangeDate"
          show-time
          style="width: 360px"
          value-format="x"
        />
        <Button :loading="loading" type="primary" @click="loadData(true)">
          搜索
        </Button>
      </div>

      <Table
        :columns="columns"
        :data-source="list"
        :loading="loading || reviewing"
        :pagination="false"
        row-key="id"
        :scroll="{ x: 1650 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userProfile'">
            <UserProfileLink :profile="record.userProfile" />
          </template>
          <template v-else-if="column.key === 'sysOrigin'">
            {{ getDisplaySysOriginText(record.sysOrigin) }}
          </template>
          <template v-else-if="column.key === 'operationType'">
            <Tag :color="record.operationType === 0 ? 'red' : 'default'">
              {{ record.operationName }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="statusColor(record.status)">
              {{ record.statusName }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'applicant'">
            <div>{{ record.applicantName || '-' }}</div>
            <div class="muted">{{ record.applicantId || '-' }}</div>
          </template>
          <template v-else-if="column.key === 'reviewer'">
            <div>{{ record.reviewerName || '-' }}</div>
            <div class="muted">{{ record.reviewerId || '-' }}</div>
          </template>
          <template v-else-if="column.key === 'time'">
            <div>申请：{{ formatDate(record.createTime) }}</div>
            <div>审核：{{ formatDate(record.reviewTime) }}</div>
            <div>执行：{{ formatDate(record.executedTime) }}</div>
          </template>
          <template v-else-if="column.key === 'actions'">
            <Space v-if="record.status === 'PENDING'">
              <Button size="small" type="link" @click="handleReview(record, true)">
                通过
              </Button>
              <Button danger size="small" type="link" @click="handleReview(record, false)">
                拒绝
              </Button>
            </Space>
            <span v-else>-</span>
          </template>
        </template>
      </Table>

      <div class="pager">
        <Pagination
          :current="query.pageIndex"
          :page-size="query.pageSize"
          :total="total"
          show-size-changer
          @change="handlePageChange"
          @showSizeChange="handlePageChange"
        />
      </div>
    </Card>
  </Page>
</template>

<style scoped>
.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

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

.muted {
  color: #8c8c8c;
  font-size: 12px;
  margin-top: 2px;
}
</style>
