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

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

import { pageResidentInviteInviter } from '#/api/legacy/resident-activity';
import AccountInput from '#/components/account-input.vue';
import InviteInviteeDetailDrawer from '#/views/resident-activity/components/invite-invitee-detail-drawer.vue';
import UserProfileLink from '#/views/operate/components/user-profile-link.vue';
import { formatDate, getAllowedSysOrigins } from '#/views/system/shared';

import {
  Button,
  Card,
  DatePicker,
  Pagination,
  Space,
  Table,
} from 'antdv-next';

defineOptions({ name: 'ResidentInviteListPage' });

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

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

const query = reactive<Record<string, any>>({
  cursor: 1,
  endTime: '',
  inviteeUserId: '',
  inviterUserId: '',
  limit: 20,
  monthKey: '',
  startTime: '',
  sysOrigin: '',
});

const columns = [
  { dataIndex: 'inviterProfile', key: 'inviterProfile', title: '邀请人', width: 280 },
  { dataIndex: 'inviteCode', key: 'inviteCode', title: '邀请码', width: 160 },
  { dataIndex: 'totalInviteCount', key: 'totalInviteCount', title: '累计邀请人数', width: 140 },
  { dataIndex: 'monthlyValidUserCount', key: 'monthlyValidUserCount', title: '月有效用户数', width: 140 },
  { dataIndex: 'totalInviteeRechargeCoins', key: 'totalInviteeRechargeCoins', title: '邀请名下总充值', width: 180 },
  { dataIndex: 'rewardGoldTotal', key: 'rewardGoldTotal', title: '已获奖励金币', width: 160 },
  { dataIndex: 'latestInviteTime', key: 'latestInviteTime', title: '最近邀请时间', width: 180 },
  { dataIndex: 'actions', key: 'actions', title: '操作', width: 100 },
];

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

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) {
    list.value = [];
    total.value = 0;
    return;
  }
  if (reset) {
    query.cursor = 1;
  }
  loading.value = true;
  try {
    const result = await pageResidentInviteInviter({ ...query });
    list.value = result.records || [];
    total.value = result.total || 0;
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  void loadData(true);
}

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

function openDetail(record: Record<string, any>) {
  activeInviter.value = record;
  detailOpen.value = true;
}
</script>

<template>
  <Page title="邀请活动列表">
    <Card>
      <div class="toolbar">
        <Space wrap>
          <SysOriginSelect
            v-model:value="query.sysOrigin"
            style="width: 140px"
            :options="sysOriginOptions"
          />
          <AccountInput
            v-model:value="query.inviterUserId"
            :sys-origin="query.sysOrigin"
            placeholder="邀请人"
            style="width: 240px"
          />
          <AccountInput
            v-model:value="query.inviteeUserId"
            :sys-origin="query.sysOrigin"
            placeholder="被邀请人"
            style="width: 240px"
          />
          <DatePicker
            v-model:value="query.monthKey"
            picker="month"
            placeholder="月份"
            style="width: 140px"
            value-format="YYYYMM"
          />
          <DatePicker.RangePicker
            v-model:value="rangeDate"
            show-time
          />
          <Button :loading="loading" type="primary" @click="handleSearch">
            搜索
          </Button>
        </Space>
      </div>

      <Table
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="false"
        row-key="inviterUserId"
        :scroll="{ x: 1380 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'inviterProfile'">
            <UserProfileLink
              :profile="{
                account: record.inviterAccount,
                id: record.inviterUserId,
                userAvatar: record.inviterAvatar,
                userNickname: record.inviterNickname,
              }"
            />
          </template>
          <template v-else-if="column.key === 'latestInviteTime'">
            {{ record.latestInviteTime ? formatDate(record.latestInviteTime) : '-' }}
          </template>
          <template v-else-if="column.key === 'actions'">
            <Button size="small" type="link" @click="openDetail(record)">
              查看明细
            </Button>
          </template>
        </template>
      </Table>

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

    <InviteInviteeDetailDrawer
      :open="detailOpen"
      :inviter-user-id="activeInviter?.inviterUserId"
      :month-key="query.monthKey"
      :sys-origin="query.sysOrigin"
      @close="detailOpen = false"
    />
  </Page>
</template>

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

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