<script setup lang="tsx">
import dayjs from 'dayjs'
import { usePageSearch } from '@/hooks'
import { AuctionStatusEnum } from '@/constants'
import { getAuctionList, getUserAuctionCount, getAuctionDetail, participateAuction } from '@/api'
import ExchangeGoodsRecordDialog from './components/exchangeGoodsRecordDilaog.vue'
import ExchangeYabiRecordDialog from './components/exchangeYabiRecordDilaog.vue'
import type { AuctionItemDto } from '@/api'
import { useYaBiStore } from '@/stores'
import { storeToRefs } from 'pinia'
import BackButton from '@/components/common/BackButton/index.vue'
import { push } from 'notivue'
const yabiStore = useYaBiStore()
const { yabiData } = storeToRefs(yabiStore)

const tabs = [
  { label: '全部', value: undefined },
  { label: '预告中', value: AuctionStatusEnum.PUBLISHED },
  { label: '竞拍中', value: AuctionStatusEnum.AUCTIONING },
  { label: '竞拍成功', value: AuctionStatusEnum.AUCTION_SUCCESS },
  { label: '已流拍', value: AuctionStatusEnum.AUCTION_FAILED },
]

let timer: NodeJS.Timeout | null = null
const { list, goToPage, changePageSize, searchParams, total, refresh } = usePageSearch(
  getAuctionList,
  {
    defaultParams: {
      status: undefined,
    },
    formatList(list) {
      return list.map((item) => {
        item.remainingTime = getCountdown(item.endTime)
        return item
      })
    },
    success(list) {
      if (timer) clearInterval(timer)
      timer = setInterval(() => {
        list.value.forEach((item) => {
          item.remainingTime = getCountdown(item.endTime)
        })
      }, 1000)
    },
  },
)

const exchangeGoodsRecordDialogRef = useTemplateRef('exchangeGoodsRecordDialogRef')
const exchangeYabiRecordDialogRef = useTemplateRef('exchangeYabiRecordDialogRef')

const getCountdown = (targetTimestamp: number) => {
  let diff = dayjs.unix(targetTimestamp).diff(dayjs(), 'second')

  if (diff <= 0) {
    return '0天 00:00:00'
  }

  const days = Math.floor(diff / 86400)
  diff %= 86400
  const hours = Math.floor(diff / 3600)
  diff %= 3600
  const minutes = Math.floor(diff / 60)
  const seconds = diff % 60

  return `${days}天 ${String(hours).padStart(2, '0')}时${String(minutes).padStart(2, '0')}分${String(seconds).padStart(2, '0')}秒`
}

const onChangeStatus = (status: AuctionStatusEnum | undefined) => {
  searchParams.value.status = status
  refresh()
}

const onOpenExchangeYabiRecordDialog = () => {
  exchangeYabiRecordDialogRef.value?.open()
}

// 根据状态计算角标样式 (从之前的 AuctionPage.vue 复制)
const getBadgeClass = (status: AuctionStatusEnum) => {
  switch (status) {
    case AuctionStatusEnum.PUBLISHED:
      return 'bg-amber-100 text-amber-700'
    case AuctionStatusEnum.AUCTION_FAILED:
      return 'bg-gray-100 text-gray-500'
    case AuctionStatusEnum.AUCTIONING:
    default:
      return 'bg-gradient-to-r from-indigo-500 to-purple-600 text-white'
  }
}

const onBid = async (item: AuctionItemDto) => {
  const isOver = await getUserAuctionCount(item.id)
  if (!isOver)
    return ElMessageBox.confirm(`您已达到竞拍次数限制${item.bidLimit}次，不可再参与竞拍`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      showCancelButton: false,
      showConfirmButton: false,
    })
  const { data: auctionDetail } = await getAuctionDetail(item.id)
  const data = reactive(auctionDetail)
  const val = ref(0)
  ElMessageBox.confirm('确定参与竞拍吗？', {
    confirmButtonText: '确认出价',
    cancelButtonText: '取消',
    customClass: 'auction-bid-dialog',
    message: () => (
      <div class="space-y-16px">
        {/* 商品名称 */}
        <div class="flex items-center gap-3">
          <img src={item.imageUrl} class="w-12 h-12 rounded-lg object-cover shadow-sm" />
          <div>
            <div class="text-15px font-600 text-gray-800 line-clamp-1">{item.name}</div>
            <div class="text-12px text-gray-400 mt-1">{item.specification}</div>
          </div>
        </div>

        {/* 规则说明 */}
        <div class="text-12px leading-18px text-indigo-500 bg-indigo-50 rounded-8px px-12px py-8px flex items-start gap-6px">
          <span class="mt-2px shrink-0">💡</span>
          <span>竞拍后将暂时扣除您出价的 YA 币，若您的出价被超越，YA 币将自动退回</span>
        </div>

        {/* 当前竞拍信息 */}
        <div class="bg-gray-50 rounded-10px p-12px space-y-8px">
          {data.currentPrice ? (
            <div class="flex items-center justify-between">
              <span class="text-13px text-gray-500">当前最高出价</span>
              <span class="text-16px text-orange-500 font-700">
                {data.currentPrice} <span class="text-12px font-400">YA币</span>
              </span>
            </div>
          ) : (
            <div class="flex items-center justify-between">
              <span class="text-13px text-gray-500">当前最高出价</span>
              <span class="text-13px text-gray-400">暂无人出价</span>
            </div>
          )}
          <div class="flex items-center justify-between">
            <span class="text-13px text-gray-500">起拍价</span>
            <span class="text-13px text-gray-700 font-500">{data.startingPrice} YA币</span>
          </div>
          <div class="flex items-center justify-between">
            <span class="text-13px text-gray-500">最低加价</span>
            <span class="text-13px text-gray-700 font-500">{data.minIncrement} YA币</span>
          </div>
          <div class="flex items-center justify-between">
            <span class="text-13px text-gray-500">出价次数上限</span>
            <span class="text-13px text-gray-700 font-500">{item.bidLimit} 次</span>
          </div>
        </div>

        {/* 出价输入 */}
        <div class="space-y-8px">
          <div class="text-13px text-gray-700 font-500">您的出价 (YA币)</div>
          <el-input-number
            v-model={val.value}
            controls-position="right"
            class="w-full!"
            min={0}
            placeholder="请输入出价金额"
          />
          <div class="flex items-center justify-end text-12px text-gray-400">
            可用余额：<span class="text-indigo-500 font-500">{yabiData.value.currentValue}</span>{' '}
            YA币
          </div>
        </div>
      </div>
    ),
    showCancelButton: true,
    showConfirmButton: true,
    beforeClose: async (action, instance, done) => {
      if (action !== 'confirm') {
        done()
      } else {
        if (val.value > yabiData.value.currentValue) return push.error('您的YA币余额不足')

        if (val.value < data.minIncrement + (data.currentPrice || data.startingPrice))
          return push.error(
            `出价必须大于等于前最高出价+最低加价幅度: 至少【${data.minIncrement + (data.currentPrice || data.startingPrice)}】YA币`,
          )

        instance.confirmButtonLoading = true
        instance.confirmButtonText = 'Loading...'
        try {
          await participateAuction(item.id, val.value)
          refresh()
          yabiStore.fetchYaBiData()
          push.success('出价成功')
          done()
        } catch (error: any) {
          console.log(error)
          if (error.code === 400 && error.message.includes('检测到刚才有人出价')) {
            // 重新获取当前竞拍信息
            const { data: newAuctionDetail } = await getAuctionDetail(item.id)
            data.currentPrice = newAuctionDetail.currentPrice
          }
          refresh()
        } finally {
          instance.confirmButtonLoading = false
          instance.confirmButtonText = '确定'
        }
      }
    },
  })
}
</script>
<template>
  <div class="xl:px-20">
    <div class="flex gap-3 relative">
      <BackButton />
      <div class="flex-3/4 min-w-0">
        <div class="bg-white/90 rounded-lg p-6 shadow-lg border border-white/60">
          <div class="flex items-center gap-3 mb-6">
            <div
              class="w-1.5 h-7 bg-gradient-to-b from-[--un-gradient-from] to-[--un-gradient-to] rounded-full shadow-sm"
              style="--un-gradient-from: #8b5cf6; --un-gradient-to: #6366f1"
            ></div>
            <h2 class="text-xl font-bold text-gray-800">限时竞拍</h2>
          </div>
          <div class="flex gap-3 text-sm mb-3 items-center flex-wrap">
            <span class="text-gray-600 font-medium">商品名称：</span>
            <el-input
              size="default"
              class="w-70"
              v-model="searchParams.name"
              placeholder="请输入商品名称"
            />
            <el-button class="rounded-lg" size="default" type="primary" @click="refresh"
              >搜索</el-button
            >
          </div>
          <div class="flex gap-3 text-sm mb-6 items-center flex-wrap">
            <span class="text-gray-600 font-medium">状态：</span>
            <button
              v-for="item in tabs"
              :key="item.value"
              class="cursor-pointer px-3 py-1.5 text-sm transition-all relative"
              @click="onChangeStatus(item.value)"
              :class="{
                'text-indigo-600 font-medium': searchParams.status === item.value,
                'text-gray-600 hover:text-gray-900': searchParams.status !== item.value,
              }"
            >
              {{ item.label }}
              <span
                v-if="searchParams.status === item.value"
                class="absolute bottom-0 left-0 right-0 h-0.5 bg-gradient-to-b from-[--un-gradient-from] to-[--un-gradient-to]"
                style="--un-gradient-from: #8b5cf6; --un-gradient-to: #6366f1"
              ></span>
            </button>
          </div>
          <template v-if="list.length">
            <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-5">
              <div
                v-for="item in list"
                :key="item.id"
                class="card group relative bg-white rounded-xl overflow-hidden border border-gray-100 shadow-sm hover:shadow-lg transition-all duration-300 cursor-pointer hover:-translate-y-0.5"
                :class="{ 'filter-grayscale-30': item.status === AuctionStatusEnum.AUCTION_FAILED }"
              >
                <!-- 图片区 -->
                <div class="card-img-wrap relative aspect-4/3 overflow-hidden bg-gray-100">
                  <img
                    :src="item.imageUrl"
                    class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                  />

                  <!-- 状态角标 -->
                  <div
                    class="absolute top-2.5 left-2.5 text-11px font-semibold px-2.5 py-1 rounded-md tracking-wide shadow-sm"
                    :class="getBadgeClass(item.status)"
                  >
                    {{ tabs.find((option) => option.value === item.status)?.label }}
                  </div>

                  <!-- 倒计时条 -->
                  <div
                    v-if="item.status === AuctionStatusEnum.AUCTIONING"
                    class="absolute bottom-0 inset-x-0 bg-black/60 text-white text-11px py-1.5 px-3 flex items-center gap-1.5"
                  >
                    <span
                      class="inline-block w-1.5 h-1.5 rounded-full bg-red-400 animate-pulse"
                    ></span>
                    {{ item.remainingTime }}
                  </div>
                </div>

                <!-- 内容区 -->
                <div class="p-4 flex flex-col gap-2">
                  <!-- 标题 + 规格 -->
                  <div class="flex items-center justify-between gap-2">
                    <h3 class="text-sm font-semibold text-gray-800 line-clamp-1">
                      {{ item.name }}
                    </h3>
                    <span class="text-11px text-gray-400 shrink-0">{{ item.specification }}</span>
                  </div>

                  <!-- 描述 -->
                  <p class="text-xs text-gray-400 line-clamp-1">
                    <el-popover :content="item.description" placement="top-start" width="300">
                      <template #reference>
                        {{ item.description }}
                      </template>
                    </el-popover>
                  </p>

                  <!-- 分隔线 -->
                  <div class="border-t border-dashed border-gray-100 my-1"></div>

                  <!-- 价格区 -->
                  <div class="flex items-end justify-between gap-2">
                    <div class="flex flex-col gap-0.5">
                      <div v-if="item.currentPrice" class="flex items-baseline gap-1">
                        <span class="text-11px text-gray-400">当前出价</span>
                        <span class="text-lg font-bold text-orange-500">{{
                          item.currentPrice
                        }}</span>
                        <span class="text-11px text-gray-400">YA币</span>
                      </div>
                      <div class="flex items-baseline gap-1">
                        <span class="text-11px text-gray-400">起拍价</span>
                        <span
                          class="font-semibold"
                          :class="
                            item.currentPrice
                              ? 'text-xs text-gray-400 line-through'
                              : 'text-lg text-orange-500'
                          "
                        >
                          {{ item.startingPrice }}
                        </span>
                        <span v-if="!item.currentPrice" class="text-11px text-gray-400">YA币</span>
                      </div>
                      <div class="text-11px text-gray-400">
                        加价幅度 ≥ {{ item.minIncrement }} YA币
                      </div>
                    </div>

                    <button
                      v-if="item.status === AuctionStatusEnum.AUCTIONING"
                      class="shrink-0 px-4 py-1.5 rounded-lg text-xs font-medium bg-gradient-to-r from-indigo-500 to-purple-500 text-white shadow-sm shadow-indigo-500/20 hover:shadow-md hover:shadow-indigo-500/30 active:scale-95 transition-all duration-200 cursor-pointer"
                      @click.stop="onBid(item)"
                    >
                      🔨 出价
                    </button>
                  </div>
                </div>
              </div>
            </div>
            <div class="flex justify-end mt-4">
              <div class="bg-gray-50 rounded-xl shadow-sm border border-gray-200 p-2">
                <el-pagination
                  v-model:current-page="searchParams.current"
                  v-model:page-size="searchParams.size"
                  :total="total"
                  @current-change="goToPage"
                  @size-change="changePageSize"
                />
              </div>
            </div>
          </template>
          <div v-else class="flex justify-center items-center py-12">
            <el-empty description="暂无" />
          </div>
        </div>
      </div>
      <!-- 右侧：信息面板 -->
      <div class="flex-1/4 space-y-6">
        <!-- YA币信息卡片 -->
        <div class="bg-white/90 rounded-lg p-6 shadow-lg border border-white/60 sticky top-[52px]">
          <div class="text-center mb-6">
            <div class="text-gray-500 text-sm mb-2">当前YA币</div>
            <div
              class="text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-purple-600 text-5xl font-bold"
            >
              {{ yabiData.currentValue }}
            </div>
          </div>
          <!-- 操作按钮 -->
          <div class="space-y-3 mb-6">
            <button
              class="cursor-pointer w-full px-4 py-3 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl text-sm font-medium hover:shadow-lg hover:scale-[1.02] transition-all duration-300"
              @click="onOpenExchangeYabiRecordDialog"
            >
              YA币收支记录
            </button>
            <!-- <button
              class="cursor-pointer w-full px-4 py-3 bg-white text-gray-700 rounded-xl text-sm font-medium border border-gray-200 hover:border-blue-400 hover:shadow-md transition-all duration-300"
              @click="onOpenExchangeGoodsRecordDialog"
            >
              商品领取列表
            </button> -->
          </div>
          <!-- 温馨提示 -->
          <!-- <div class="bg-amber-50 border border-amber-200/60 rounded-xl p-4">
            <div class="flex items-start gap-2">
              <svg
                class="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fill-rule="evenodd"
                  d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                  clip-rule="evenodd"
                />
              </svg>
              <div class="text-sm text-gray-700">
                <div class="font-medium mb-1">温馨提示</div>
                <p class="text-xs leading-relaxed">
                  实物商品兑换后，请耐心等待各地人才发展部伙伴统一发放安排
                </p>
              </div>
            </div>
          </div> -->
          <!-- <div class="mt-6 pt-6 border-t border-gray-100 space-y-3">
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-500">实物商品</span>
              <span class="font-medium text-gray-700">{{ total }} 件</span>
            </div>
          </div> -->
        </div>
      </div>
    </div>
    <ExchangeGoodsRecordDialog ref="exchangeGoodsRecordDialogRef" />
    <ExchangeYabiRecordDialog ref="exchangeYabiRecordDialogRef" />
  </div>
</template>

<style scoped>
.card.filter-grayscale-30 {
  filter: grayscale(30%);
}
</style>

<style>
.auction-bid-dialog .el-message-box__header {
  display: none;
}

.auction-bid-dialog .el-message-box__content {
  padding: 24px 24px 8px;
}

.auction-bid-dialog .el-message-box__btns {
  padding: 12px 24px 20px;
}

.auction-bid-dialog .el-message-box__btns .el-button--primary {
  background: linear-gradient(to right, #6366f1, #8b5cf6);
  border: none;
  border-radius: 8px;
  padding: 8px 24px;
}

.auction-bid-dialog .el-message-box__btns .el-button--primary:hover {
  opacity: 0.9;
}

.auction-bid-dialog .el-message-box__btns .el-button:not(.el-button--primary) {
  border-radius: 8px;
  padding: 8px 24px;
}

.auction-bid-dialog {
  border-radius: 16px !important;
  overflow: hidden;
}

.auction-bid-dialog .el-message-box__status {
  display: none !important;
}
</style>
