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

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

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

import { pageGmVipGift, submitGmVipGift } 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: 'GmVipGift' });

const VIP_OPTIONS = [1, 2, 3, 4, 5].map((level) => ({
  label: `VIP${level}`,
  value: level,
}));

const loading = ref(false);
const submitting = ref(false);
const open = 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: '',
  pageIndex: 1,
  pageSize: 20,
  startTime: '',
  status: '',
  userId: '',
  vipLevel: undefined as number | undefined,
});

const form = reactive({
  remarks: '',
  userSearch: '',
  vipLevel: 1,
});

const columns = [
  { dataIndex: 'userProfile', key: 'userProfile', title: '获赠用户', width: 240 },
  { dataIndex: 'sysOrigin', key: 'sysOrigin', title: '系统', width: 100 },
  { dataIndex: 'vipLevel', key: 'vipLevel', title: '赠送VIP', width: 110 },
  { dataIndex: 'fromLevel', key: 'fromLevel', title: '原VIP', width: 110 },
  { dataIndex: 'durationDays', key: 'durationDays', title: '天数', width: 90 },
  { dataIndex: 'status', key: 'status', title: '状态', width: 100 },
  { dataIndex: 'expireAt', key: 'expireAt', title: '到期时间', width: 180 },
  { dataIndex: 'applicant', key: 'applicant', title: '操作人', width: 160 },
  { dataIndex: 'remarks', key: 'remarks', title: '备注', width: 240 },
  { dataIndex: 'createTime', key: 'createTime', title: '操作时间', width: 180 },
];

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 resolveUserIdValue(value: unknown, required = false) {
  const parsed = parseEncodedValue(value);
  const content = String(parsed.content || '').trim();
  if (!content) {
    if (required) {
      message.warning('请输入用户ID');
      return null;
    }
    return '';
  }
  if (!parsed.accountType || parsed.accountType === 'LONG') {
    return content.replace(/[^\d]/g, '');
  }
  if (!parsed.sysOrigin) {
    message.warning('请选择系统');
    return null;
  }
  const result = await getUserBaseInfoBySysOriginAccount(parsed.sysOrigin, content);
  const userId = result?.id || result?.userId;
  if (!userId) {
    message.warning('未找到用户');
    return null;
  }
  return String(userId);
}

function resetForm() {
  form.remarks = '';
  form.userSearch = '';
  form.vipLevel = 1;
}

function statusColor(status?: string) {
  return status === 'SUCCESS' ? 'success' : 'default';
}

async function loadData(reset = false) {
  if (reset) {
    query.pageIndex = 1;
  }
  const resolvedUserId = await resolveUserIdValue(userSearch.value);
  if (resolvedUserId === null) {
    return;
  }
  loading.value = true;
  try {
    query.userId = resolvedUserId;
    const result = await pageGmVipGift({
      ...query,
      applicantId: query.applicantId || undefined,
      status: query.status || undefined,
      userId: query.userId || undefined,
      vipLevel: query.vipLevel,
    });
    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();
}

async function handleSubmit() {
  const userId = await resolveUserIdValue(form.userSearch, true);
  if (!userId) {
    return;
  }
  if (!form.vipLevel) {
    message.warning('请选择VIP等级');
    return;
  }
  if (!String(form.remarks || '').trim()) {
    message.warning('请输入备注');
    return;
  }
  submitting.value = true;
  try {
    await submitGmVipGift({
      remarks: form.remarks,
      userId,
      vipLevel: form.vipLevel,
    });
    message.success('VIP已赠送');
    open.value = false;
    resetForm();
    await loadData(true);
  } finally {
    submitting.value = false;
  }
}

void loadData(true);
</script>

<template>
  <Page title="VIP赠送">
    <Card>
      <div class="page-head">
        <div class="page-head__title">VIP赠送记录</div>
        <Button type="primary" @click="open = true">赠送</Button>
      </div>

      <div class="toolbar">
        <Select
          v-model:value="query.vipLevel"
          allow-clear
          placeholder="VIP等级"
          style="width: 140px"
          :options="VIP_OPTIONS"
        />
        <Select
          v-model:value="query.status"
          allow-clear
          placeholder="状态"
          style="width: 140px"
          :options="[{ label: '已赠送', value: 'SUCCESS' }]"
        />
        <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"
        :pagination="false"
        row-key="id"
        :scroll="{ x: 1400 }"
      >
        <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 === 'vipLevel'">
            <Tag color="blue">{{ record.levelCode || `VIP${record.vipLevel}` }}</Tag>
          </template>
          <template v-else-if="column.key === 'fromLevel'">
            {{ record.fromLevelName || '非VIP' }}
          </template>
          <template v-else-if="column.key === 'durationDays'">
            {{ record.durationDays || 30 }}
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="statusColor(record.status)">
              {{ record.statusName || record.status || '-' }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'expireAt'">
            {{ formatDate(record.expireAt) }}
          </template>
          <template v-else-if="column.key === 'applicant'">
            {{ record.applicantName || record.applicantId || '-' }}
          </template>
          <template v-else-if="column.key === 'remarks'">
            {{ record.remarks || '-' }}
          </template>
          <template v-else-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>
        </template>
      </Table>

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

    <Modal
      v-model:open="open"
      title="VIP赠送"
      :confirm-loading="submitting"
      width="560px"
      @cancel="resetForm"
      @ok="handleSubmit"
    >
      <Form layout="vertical">
        <FormItem label="用户ID">
          <AccountInput
            v-model:value="form.userSearch"
            default-select-type="LONG"
            placeholder="请输入长ID或短ID"
          />
        </FormItem>
        <FormItem label="VIP等级">
          <Select v-model:value="form.vipLevel" :options="VIP_OPTIONS" />
        </FormItem>
        <FormItem label="有效期">
          <Input value="30天" disabled />
        </FormItem>
        <FormItem label="备注">
          <TextArea
            v-model:value="form.remarks"
            :maxlength="500"
            :rows="4"
            show-count
            placeholder="请输入赠送原因"
          />
        </FormItem>
      </Form>
    </Modal>
  </Page>
</template>

<style scoped>
.page-head {
  align-items: center;
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.page-head__title {
  color: #111827;
  font-size: 16px;
  font-weight: 600;
}

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

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