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

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

import {
  getResidentRegisterRewardConfig,
  pageResidentRegisterRewardDailyRecords,
  resetResidentRegisterRewardConfig,
  saveResidentRegisterRewardConfig,
} from '#/api/legacy/resident-activity';
import ActivityResourceGroupSelectDrawer from '#/views/props/components/activity-resource-group-select-drawer.vue';
import UserProfileLink from '#/views/operate/components/user-profile-link.vue';
import { getAllowedSysOrigins } from '#/views/system/shared';

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

defineOptions({ name: 'ResidentRegisterRewardConfigPage' });

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

const loading = ref(false);
const saving = ref(false);
const recordLoading = ref(false);
const recordTotal = ref(0);
const groupPickerOpen = ref(false);
const recordList = ref<Array<Record<string, any>>>([]);

const form = reactive<Record<string, any>>({
  configured: false,
  dailyLimit: 0,
  enabled: false,
  goldAmount: 0,
  rewardGroupId: null,
  rewardGroupName: '',
  sysOrigin: '',
});

const recordQuery = reactive<Record<string, any>>({
  claimDate: '',
  cursor: 1,
  limit: 20,
});

const recordSummary = reactive<Record<string, any>>({
  dailyLimit: 0,
  date: '',
  issuedCount: 0,
  limitEnabled: false,
  occupiedCount: 0,
  remainingCount: 0,
  successCount: 0,
});

const statusMeta = computed(() => {
  if (!form.configured) {
    return {
      color: 'processing',
      description: '当前未配置，普通注册成功后不会发放注册奖励。',
      text: '未配置',
    };
  }
  if (form.enabled) {
    return {
      color: 'success',
      description:
        form.dailyLimit > 0
          ? `当前已启用，每日最多发放 ${form.dailyLimit} 份注册奖励。`
          : '当前已启用，注册后会按下面配置发金币和/或奖励组。',
      text: '已启用',
    };
  }
  return {
    color: 'default',
    description: '当前已明确关闭，普通注册成功后不发任何注册奖励。',
    text: '已关闭',
  };
});

const recordColumns = [
  { dataIndex: 'user', key: 'user', title: '领取用户', width: 280 },
  { dataIndex: 'claimResult', key: 'claimResult', title: '领取结果', width: 220 },
  { dataIndex: 'status', key: 'status', title: '处理状态', width: 120 },
  { dataIndex: 'rewardPayload', key: 'rewardPayload', title: '奖励内容', width: 220 },
  { dataIndex: 'claimDate', key: 'claimDate', title: '领取日期', width: 120 },
  { dataIndex: 'createTime', key: 'createTime', title: '触发时间', width: 180 },
  { dataIndex: 'errorMessage', key: 'errorMessage', title: '备注 / 失败原因', width: 260 },
];

function normalizeConfig(result: Record<string, any> | null | undefined) {
  const value = result ?? {};
  form.configured = Boolean(value.configured);
  form.dailyLimit = Number(value.dailyLimit || 0);
  form.enabled = Boolean(value.enabled);
  form.goldAmount = Number(value.goldAmount || 0);
  form.rewardGroupId = value.rewardGroupId ?? null;
  form.rewardGroupName = String(value.rewardGroupName || '');
  form.sysOrigin = String(value.sysOrigin || form.sysOrigin || sysOriginOptions.value[0]?.value || '');
}

function syncRecordSummary(result: Record<string, any> | null | undefined) {
  const value = result ?? {};
  recordSummary.date = String(value.date || recordSummary.date || '');
  recordSummary.dailyLimit = Number(value.dailyLimit || 0);
  recordSummary.limitEnabled = Boolean(value.limitEnabled);
  recordSummary.occupiedCount = Number(value.occupiedCount || 0);
  recordSummary.issuedCount = Number(value.issuedCount || 0);
  recordSummary.successCount = Number(value.successCount || 0);
  recordSummary.remainingCount = Number(value.remainingCount || 0);
}

function claimResultColor(result: string) {
  switch (String(result || '').toUpperCase()) {
    case 'REWARDED':
      return 'success';
    case 'QUOTA_EXHAUSTED':
      return 'warning';
    case 'FAILED':
      return 'error';
    case 'SKIPPED':
      return 'default';
    default:
      return 'processing';
  }
}

function processStatusColor(status: string) {
  switch (String(status || '').toUpperCase()) {
    case 'SUCCESS':
      return 'success';
    case 'FAILED':
      return 'error';
    case 'SKIPPED':
      return 'default';
    default:
      return 'processing';
  }
}

async function loadConfig() {
  if (!form.sysOrigin) {
    return;
  }
  loading.value = true;
  try {
    const result = await getResidentRegisterRewardConfig(form.sysOrigin);
    normalizeConfig(result);
  } finally {
    loading.value = false;
  }
}

async function loadDailyRecords(reset = false) {
  if (!form.sysOrigin) {
    recordList.value = [];
    recordTotal.value = 0;
    return;
  }
  if (reset) {
    recordQuery.cursor = 1;
  }
  recordLoading.value = true;
  try {
    const result = await pageResidentRegisterRewardDailyRecords({
      ...recordQuery,
      sysOrigin: form.sysOrigin,
    });
    recordList.value = Array.isArray(result.records) ? result.records : [];
    recordTotal.value = Number(result.total || 0);
    syncRecordSummary(result);
    if (!recordQuery.claimDate && result.date) {
      recordQuery.claimDate = String(result.date);
    }
  } finally {
    recordLoading.value = false;
  }
}

async function loadData() {
  await Promise.all([loadConfig(), loadDailyRecords(true)]);
}

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

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

function openRewardPicker() {
  groupPickerOpen.value = true;
}

function clearRewardGroup() {
  form.rewardGroupId = null;
  form.rewardGroupName = '';
}

function handleRewardGroupSelect(row: Record<string, any>) {
  form.rewardGroupId = row.id;
  form.rewardGroupName = row.name;
  groupPickerOpen.value = false;
}

async function submitForm() {
  saving.value = true;
  try {
    await saveResidentRegisterRewardConfig({
      dailyLimit: Number(form.dailyLimit || 0),
      enabled: Boolean(form.enabled),
      goldAmount: Number(form.goldAmount || 0),
      rewardGroupId: form.rewardGroupId ?? null,
      sysOrigin: form.sysOrigin,
    });
    message.success('保存成功');
    await loadData();
  } finally {
    saving.value = false;
  }
}

function handleSave() {
  Modal.confirm({
    async onOk() {
      await submitForm();
    },
    title: '确认保存当前系统的注册奖励配置？',
  });
}

function handleReset() {
  Modal.confirm({
    async onOk() {
      saving.value = true;
      try {
        await resetResidentRegisterRewardConfig(form.sysOrigin);
        message.success('已清空当前系统的注册奖励配置');
        await loadData();
      } finally {
        saving.value = false;
      }
    },
    title: '确认清空当前系统的注册奖励配置？',
    content: '清空后会删除当前系统的后台配置，普通注册成功后不再发放注册奖励。',
  });
}

function handleRecordSearch() {
  void loadDailyRecords(true);
}

function handleRecordPageChange(page: number, pageSize: number) {
  recordQuery.cursor = page;
  recordQuery.limit = pageSize;
  void loadDailyRecords();
}
</script>

<template>
  <Page auto-content-height>
    <Spin :spinning="loading">
      <Card :bordered="false" title="注册奖励配置">
        <Space class="toolbar" wrap>
          <Select
            v-model:value="form.sysOrigin"
            :options="sysOriginOptions"
            option-filter-prop="label"
            option-label-prop="label"
            placeholder="请选择系统"
            show-search
            style="width: 180px"
          />
          <Tag :color="statusMeta.color">
            {{ statusMeta.text }}
          </Tag>
          <span class="status-desc">{{ statusMeta.description }}</span>
        </Space>

        <div class="section">
          <div class="field-label">启用后台注册奖励</div>
          <Switch v-model:checked="form.enabled" />
        </div>

        <div class="section">
          <div class="field-label">赠送金币</div>
          <InputNumber
            v-model:value="form.goldAmount"
            :disabled="!form.enabled"
            :min="0"
            :precision="0"
            placeholder="请输入金币数量"
            style="width: 240px"
          />
        </div>

        <div class="section">
          <div class="field-label">每日限制份数</div>
          <InputNumber
            v-model:value="form.dailyLimit"
            :disabled="!form.enabled"
            :min="0"
            :precision="0"
            placeholder="0 表示不限"
            style="width: 240px"
          />
          <span class="field-desc">0 表示不限，超过当天限额后新用户会视为领取成功但不再真实发奖。</span>
        </div>

        <div class="section">
          <div class="field-label">赠送奖励组</div>
          <Space wrap>
            <Button :disabled="!form.enabled" @click="openRewardPicker">
              {{ form.rewardGroupId ? '更换奖励组' : '选择奖励组' }}
            </Button>
            <Button
              v-if="form.rewardGroupId"
              :disabled="!form.enabled"
              danger
              type="link"
              @click="clearRewardGroup"
            >
              清空
            </Button>
            <span v-if="form.rewardGroupId" class="reward-group">
              {{ form.rewardGroupName }} (ID: {{ form.rewardGroupId }})
            </span>
            <span v-else class="reward-group empty">
              未选择奖励组
            </span>
          </Space>
        </div>

        <div class="tips">
          <div>未配置：注册成功后不发奖励。</div>
          <div>已启用：可以同时送金币和奖励组，两者至少配置一个。</div>
          <div>每日限制份数：达到上限后，后续用户会直接记为领取成功，不再真实发奖。</div>
        </div>

        <Space class="actions" wrap>
          <Button :loading="saving" type="primary" @click="handleSave">
            保存配置
          </Button>
          <Button :loading="saving" @click="handleReset">
            清空配置
          </Button>
        </Space>
      </Card>

      <Card :bordered="false" class="record-card" title="每日领取记录">
        <div class="toolbar">
          <Space wrap>
            <DatePicker
              v-model:value="recordQuery.claimDate"
              placeholder="领取日期"
              style="width: 160px"
              value-format="YYYY-MM-DD"
            />
            <Button :loading="recordLoading" type="primary" @click="handleRecordSearch">
              查询
            </Button>
          </Space>
        </div>

        <div class="summary">
          <Tag color="processing">
            统计日期：{{ recordSummary.date || '-' }}
          </Tag>
          <Tag color="purple">
            每日限额：{{ recordSummary.limitEnabled ? `${recordSummary.dailyLimit} 份` : '不限' }}
          </Tag>
          <Tag color="orange">
            已占用名额：{{ recordSummary.occupiedCount }}
          </Tag>
          <Tag color="success">
            已发放成功：{{ recordSummary.issuedCount }}
          </Tag>
          <Tag color="cyan">
            领取成功人数：{{ recordSummary.successCount }}
          </Tag>
          <Tag color="default">
            剩余名额：{{ recordSummary.limitEnabled ? `${recordSummary.remainingCount} 份` : '不限' }}
          </Tag>
        </div>

        <Table
          :columns="recordColumns"
          :data-source="recordList"
          :loading="recordLoading"
          :pagination="false"
          row-key="id"
          :scroll="{ x: 1280 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'user'">
              <UserProfileLink
                :profile="{
                  account: record.account,
                  countryCode: record.countryCode,
                  countryName: record.countryName,
                  id: record.userId,
                  userAvatar: record.userAvatar,
                  userNickname: record.userNickname,
                }"
              />
            </template>
            <template v-else-if="column.key === 'claimResult'">
              <Tag :color="claimResultColor(record.claimResult)">
                {{ record.claimResultText || '-' }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'status'">
              <Tag :color="processStatusColor(record.status)">
                {{ record.status || '-' }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'rewardPayload'">
              <div>金币：{{ record.goldAmount || 0 }}</div>
              <div>奖励组：{{ record.rewardGroupId || '-' }}</div>
            </template>
            <template v-else-if="column.key === 'errorMessage'">
              {{ record.errorMessage || '-' }}
            </template>
          </template>
        </Table>

        <div v-if="recordTotal > 0" class="pager">
          <Pagination
            :current="recordQuery.cursor"
            :page-size="recordQuery.limit"
            :total="recordTotal"
            show-size-changer
            @change="handleRecordPageChange"
            @showSizeChange="handleRecordPageChange"
          />
        </div>
      </Card>

      <ActivityResourceGroupSelectDrawer
        :open="groupPickerOpen"
        :sys-origin="form.sysOrigin"
        @close="groupPickerOpen = false"
        @select="handleRewardGroupSelect"
      />
    </Spin>
  </Page>
</template>

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

.status-desc {
  color: rgb(100 116 139);
}

.section {
  align-items: center;
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.field-label {
  color: rgb(15 23 42);
  flex: 0 0 120px;
  font-weight: 600;
}

.field-desc {
  color: rgb(100 116 139);
}

.reward-group {
  color: rgb(15 23 42);
}

.reward-group.empty {
  color: rgb(148 163 184);
}

.tips {
  background: rgb(248 250 252);
  border-radius: 12px;
  color: rgb(71 85 105);
  line-height: 1.8;
  margin-top: 12px;
  padding: 16px;
}

.actions {
  margin-top: 24px;
}

.record-card {
  margin-top: 16px;
}

.summary {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

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