<template>
  <div class="user-card" :class="{ 'user-card--goods': props.type === 'goods' }">
    <div class="user-card__main">
      <div class="user-card__stat">
        <span class="user-card__label">剩余乐跑次数</span>
        <div class="user-card__stat-row">
          <a-statistic
            :value="userCount?.lepao_count ?? 0"
            :value-style="{ fontSize: '2rem', fontWeight: 700, color: 'var(--stat-color)' }"
            animation
            show-group-separator
          />
          <div class="vip-strip" :class="{ 'vip-strip--active': isVip }" @click="router.push('/ai/assistant')">
            <span class="vip-strip__badge">VIP</span>
            <span class="vip-strip__text">{{ vipText }}</span>
            <icon-right class="vip-strip__arrow" />
          </div>
        </div>
      </div>
      <div class="user-card__actions">
        <a-button
          v-if="props.type === 'lepao'"
          type="primary"
          size="large"
          class="action-btn action-btn--primary"
          @click="$router.push('/store/goodsList')"
        >
          <icon-fire /> 去购买
        </a-button>
        <a-button
          v-else
          type="primary"
          size="large"
          class="action-btn action-btn--primary"
          @click="$router.push('/lepao/accountList')"
        >
          <icon-thunderbolt />&nbsp;去乐跑
        </a-button>
        <a-button
          v-if="hasPermission('action.goods.sendCount')"
          size="large"
          class="action-btn"
          @click="SendCount"
        >
          <icon-gift />&nbsp;赠送
        </a-button>
        <a-button size="large" class="action-btn" @click="goCountLedger">
          <icon-list />&nbsp;明细
        </a-button>
      </div>
    </div>
  </div>

  <a-modal
    v-model:visible="visible"
    title="赠送乐跑次数"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
    :ok-loading="ok_loading"
    unmount-on-close
  >
    <a-form :model="sendform" layout="vertical">
      <a-form-item field="username" label="接收人用户名">
        <a-input
          v-model="sendform.username"
          placeholder="如：用户adfg45g"
          :max-length="20"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="count" label="赠送次数">
        <a-input-number v-model="sendform.count" :min="1" :max="9999" mode="button" />
      </a-form-item>
    </a-form>
    <div v-if="hasPermission('action.goods.sendCount')" class="send-modal-extra">
      <a-link @click="goSendCountRecords">
        <icon-list />&nbsp;赠送记录
      </a-link>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, reactive, onUnmounted, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getCount, sendCount } from '@/api/goods'
import { Notification, Message } from '@arco-design/web-vue'
import { hasPermission } from '@/utils/permission'

const props = defineProps({
  type: { type: String, default: 'lepao' }
})

const userCount = ref({ lepao_count: 0 })
const router = useRouter()
const visible = ref(false)
const ok_loading = ref(false)
const sendform = reactive({ username: '', count: 1 })

const isVip = computed(() => {
  const expire = Number(userCount.value?.vip_expire_time || 0)
  return expire > Date.now() || (Number(userCount.value?.vip || 0) === 1 && expire === 0)
})

const vipText = computed(() => {
  const expire = Number(userCount.value?.vip_expire_time || 0)
  if (!isVip.value) return '开通会员'
  if (!expire) return '永久会员'
  return `VIP 至 ${new Date(expire).toLocaleDateString('zh-CN')}`
})

const handleBeforeOk = async (done) => {
  if (!hasPermission('action.goods.sendCount')) {
    Notification.warning({ title: '无权限', content: '当前账号暂无赠送权限' })
    return false
  }
  try {
    ok_loading.value = true
    if (!sendform.username) {
      Message.error('请填写接收人用户名')
      return false
    }
    if (!sendform.count || sendform.count < 1 || sendform.count > 9999) {
      Notification.error({ title: '赠送失败', content: '赠送次数需在 1～9999 之间' })
      return false
    }
    const res = await sendCount({ username: sendform.username, count: sendform.count })
    if (!res || res.code !== 0) {
      Notification.error({ title: '赠送失败', content: res?.msg ?? '请稍后再试' })
      return false
    }
    Message.success(res.msg || '赠送成功')
    done()
    GetCount()
  } catch (error) {
    Notification.error({ title: '赠送失败', content: error.message || '请稍后再试' })
    return false
  } finally {
    ok_loading.value = false
  }
}

const handleCancel = () => {
  visible.value = false
}

const SendCount = () => {
  sendform.username = ''
  sendform.count = 1
  visible.value = true
}

const goCountLedger = () => router.push('/lepao/countLedger')

const goSendCountRecords = () => {
  visible.value = false
  router.push('/store/sendCountRecords')
}

const GetCount = async () => {
  try {
    const res = await getCount()
    if (!res || res.code !== 0) return
    userCount.value = res.data
  } catch {
    /* 静默失败，避免轮询刷屏 */
  }
}

let timer = null
const startPolling = () => {
  if (!timer) timer = setInterval(GetCount, 8000)
}
const stopPolling = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

onMounted(async () => {
  await GetCount()
  startPolling()
})
onUnmounted(stopPolling)
</script>

<style scoped lang="less">
@import '@/styles/store-theme.less';

.user-card {
  --stat-color: rgb(var(--primary-6));
  background: @store-card-bg;
  border: 1px solid @store-card-border;
  border-radius: @store-radius;
  box-shadow: @store-shadow;
  padding: 20px 24px;

  &--goods {
    background: linear-gradient(135deg, #f4faf6 0%, #e8f5ec 100%);
    --stat-color: @store-primary;
  }

  &__main {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
  }

  &__label {
    display: block;
    font-size: 0.85rem;
    color: @store-text-muted;
    margin-bottom: 4px;
  }

  &__stat-row {
    display: flex;
    flex-wrap: wrap;
    align-items: baseline;
    gap: 10px;

    :deep(.arco-statistic) {
      flex: 0 0 auto;
    }
  }

  &__actions {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
}

.vip-strip {
  display: inline-flex;
  align-items: center;
  align-self: center;
  gap: 6px;
  min-height: 28px;
  max-width: min(210px, 100%);
  padding: 4px 7px 4px 5px;
  border: 1px solid rgba(236, 133, 171, 0.18);
  border-radius: 999px;
  background: linear-gradient(135deg, rgba(255, 246, 250, 0.96), rgba(255, 250, 240, 0.92));
  color: #94465f;
  font-size: 12px;
  cursor: pointer;
  box-shadow: 0 8px 18px rgba(236, 133, 171, 0.08);
  transition: border-color 0.18s ease, box-shadow 0.18s ease, transform 0.18s ease;

  &:hover {
    border-color: rgba(236, 133, 171, 0.34);
    box-shadow: 0 10px 22px rgba(236, 133, 171, 0.12);
    transform: translateY(-1px);
  }

  &--active {
    border-color: rgba(249, 168, 212, 0.3);
    background: linear-gradient(135deg, rgba(255, 245, 248, 0.98), rgba(255, 247, 237, 0.96));
    color: #8f3f58;
    box-shadow: 0 8px 18px rgba(249, 168, 212, 0.1);
  }

  &__badge {
    display: inline-grid;
    place-items: center;
    height: 18px;
    min-width: 30px;
    padding: 0 6px;
    border-radius: 999px;
    background: linear-gradient(135deg, #f9a8d4, #8b5cf6);
    color: #fff;
    font-size: 10px;
    font-weight: 900;
    box-shadow: 0 6px 14px rgba(139, 92, 246, 0.18);
  }

  &__text {
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &__arrow {
    flex: 0 0 auto;
    font-size: 11px;
    opacity: 0.56;
  }
}

.action-btn {
  border-radius: 999px;

  &--primary {
    background: @store-primary !important;
    border-color: @store-primary !important;
  }
}

.send-modal-extra {
  margin-top: 4px;
  text-align: center;
}

@media (max-width: 640px) {
  .user-card__stat-row {
    align-items: flex-start;
    gap: 8px;
  }

  .vip-strip {
    width: auto;
    max-width: 100%;
    justify-content: flex-start;
  }
}
</style>
