<template>
  <div class="relative">
    <BackButton />
    <div class="flex gap-6">
      <!-- 左侧：商品列表区域 -->
      <div class="flex-3/4 min-w-0">
        <!-- 虚拟装饰区域 -->
        <div
          class="bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg mb-6 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-[#8b5cf6] to-[#6366f1] rounded-full shadow-sm"
            ></div>
            <h2 class="text-xl font-bold text-gray-800">虚拟装饰</h2>
          </div>

          <template v-if="virtualGoodsList.length">
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
              <div
                v-for="item in virtualGoodsList"
                :key="item.id"
                class="goods-card group relative bg-white rounded-xl overflow-hidden cursor-pointer border border-gray-200/80 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
                @click="onExchangeGoods(item)"
              >
                <div
                  class="aspect-square bg-gradient-to-br from-gray-50 to-gray-100/80 overflow-hidden p-5 flex items-center justify-center"
                >
                  <img
                    :src="item.imageUrl"
                    alt=""
                    class="max-w-full max-h-full object-contain rounded-lg transition-transform duration-300 group-hover:scale-110"
                  />
                </div>
                <div class="p-3.5 border-t border-gray-100">
                  <div
                    class="text-13px text-gray-800 font-medium line-clamp-2 min-h-[36px] leading-snug"
                  >
                    {{ item.name }}
                  </div>
                  <div class="mt-2.5 flex items-center justify-between">
                    <div class="flex items-baseline gap-0.5">
                      <span class="text-xs text-orange-400 font-medium">¥</span>
                      <span class="text-xl font-bold text-orange-500">{{ item.price }}</span>
                      <span class="text-11px text-gray-400 ml-0.5">积分</span>
                    </div>
                    <span class="text-11px text-gray-300">库存 {{ item.stock }}</span>
                  </div>
                </div>
                <div
                  class="absolute inset-x-0 bottom-0 h-0.75 bg-gradient-to-r from-indigo-400 to-purple-400 scale-x-0 group-hover:scale-x-100 transition-transform duration-300 origin-left"
                ></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
                  size="small"
                  v-model:current-page="virtualGoodsSearchParams.current"
                  v-model:page-size="virtualGoodsSearchParams.size"
                  :total="virtualGoodsTotal"
                  @current-change="virtualGoodsGoToPage"
                  @size-change="virtualGoodsChangePageSize"
                />
              </div>
            </div>
          </template>
          <div v-else class="flex justify-center items-center py-12">
            <el-empty description="暂无" />
          </div>
        </div>

        <!-- 实物奖品区域 -->
        <div class="bg-white/90 backdrop-blur-sm rounded-2xl 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-[#8b5cf6] to-[#6366f1] rounded-full shadow-sm"
            ></div>
            <h2 class="text-xl font-bold text-gray-800">亚声实物</h2>
          </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="onChangeRegion(item.value)"
              :class="{
                'text-indigo-600 font-medium': realGoodsSearchParams.region === item.value,
                'text-gray-600 hover:text-gray-900': realGoodsSearchParams.region !== item.value,
              }"
            >
              {{ item.label }}
              <span
                v-if="realGoodsSearchParams.region === item.value"
                class="absolute bottom-0 left-0 right-0 h-0.5 bg-gradient-to-b from-[#8b5cf6] to-[#6366f1]"
              ></span>
            </button>
          </div>

          <template v-if="realGoodsList.length">
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
              <div
                v-for="item in realGoodsList"
                :key="item.id"
                class="goods-card group relative bg-white rounded-xl overflow-hidden cursor-pointer border border-gray-200/80 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-300"
                @click="onExchangeGoods(item)"
              >
                <div
                  class="aspect-square bg-gradient-to-br from-gray-50 to-gray-100/80 overflow-hidden p-5 flex items-center justify-center"
                >
                  <img
                    :src="item.imageUrl"
                    alt=""
                    class="max-w-full max-h-full object-contain rounded-lg transition-transform duration-300 group-hover:scale-110"
                  />
                </div>
                <div class="p-3.5 border-t border-gray-100">
                  <div
                    class="text-13px text-gray-800 font-medium line-clamp-2 min-h-[36px] leading-snug"
                  >
                    {{ item.name }}
                  </div>
                  <div class="mt-2.5 flex items-center justify-between">
                    <div class="flex items-baseline gap-0.5">
                      <span class="text-xs text-orange-400 font-medium">¥</span>
                      <span class="text-xl font-bold text-orange-500">{{ item.price }}</span>
                      <span class="text-11px text-gray-400 ml-0.5">积分</span>
                    </div>
                    <span class="text-11px text-gray-300">库存 {{ item.stock }}</span>
                  </div>
                </div>
                <div
                  class="absolute inset-x-0 bottom-0 h-0.75 bg-gradient-to-r from-indigo-400 to-purple-400 scale-x-0 group-hover:scale-x-100 transition-transform duration-300 origin-left"
                ></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="realGoodsSearchParams.current"
                  v-model:page-size="realGoodsSearchParams.size"
                  :total="realGoodsTotal"
                  @current-change="realGoodsGoToPage"
                  @size-change="realGoodsChangePageSize"
                />
              </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 flex-shrink-0 space-y-6">
        <!-- YA币信息卡片 -->
        <div
          class="bg-white/90 backdrop-blur-sm rounded-2xl 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">
                  实物商品兑换后，请耐心等待各地人才发展部伙伴统一发放安排
                  <!-- <span class="text-blue-600 cursor-pointer hover:underline ml-1">查看联系人</span> -->
                </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">{{ virtualGoodsTotal }} 件</span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-500">实物商品</span>
              <span class="font-medium text-gray-700">{{ realGoodsTotal }} 件</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <ExchangeGoodsRecordDialog ref="exchangeGoodsRecordDialogRef" />
    <ExchangeYabiRecordDialog ref="exchangeYabiRecordDialogRef" />
  </div>
</template>

<script setup lang="tsx">
import { exchangeGoods, getShopItemList } from '@/api'
import { usePageSearch } from '@/hooks'
import { regionListOptions, ShopGoodsTypeEnum } from '@/constants'
import type { ExchangeGoodsParams, BackendShopItemDto } from '@/api'
import ExchangeContent from './components/exchangeContent.tsx'
import ExchangeGoodsRecordDialog from './components/exchangeGoodsRecordDilaog.vue'
import ExchangeYabiRecordDialog from './components/exchangeYabiRecordDilaog.vue'
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 activeTab = ref('深圳')
const tabs = ref(regionListOptions)

const exchangeGoodsRecordDialogRef = useTemplateRef<InstanceType<typeof ExchangeGoodsRecordDialog>>(
  'exchangeGoodsRecordDialogRef',
)
const exchangeYabiRecordDialogRef = useTemplateRef<InstanceType<typeof ExchangeYabiRecordDialog>>(
  'exchangeYabiRecordDialogRef',
)

// 虚拟商品
const {
  list: virtualGoodsList,
  goToPage: virtualGoodsGoToPage,
  changePageSize: virtualGoodsChangePageSize,
  searchParams: virtualGoodsSearchParams,
  total: virtualGoodsTotal,
} = usePageSearch(getShopItemList, {
  defaultParams: {
    itemType: ShopGoodsTypeEnum.VIRTUAL_GOODS,
  },
})

// 实物商品
const {
  list: realGoodsList,
  goToPage: realGoodsGoToPage,
  changePageSize: realGoodsChangePageSize,
  searchParams: realGoodsSearchParams,
  total: realGoodsTotal,
} = usePageSearch(getShopItemList, {
  defaultParams: {
    itemType: ShopGoodsTypeEnum.REAL_GOODS,
    region: activeTab.value,
  },
})

const onChangeRegion = (region: string) => {
  realGoodsSearchParams.value.region = region
  realGoodsGoToPage(1)
}

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

const onOpenExchangeGoodsRecordDialog = () => {
  exchangeGoodsRecordDialogRef.value?.open()
}

// 兑换商品

const onExchangeGoods = async (item: BackendShopItemDto) => {
  const form = ref<ExchangeGoodsParams>({
    itemId: item.id,
    num: 1,
  })
  if (item.itemType === ShopGoodsTypeEnum.REAL_GOODS) {
    form.value.deliveryInfo = '广州'
  }

  await ElMessageBox({
    title: 'YA币兑换',
    customClass: 'exchange-dialog',
    message: () => (
      // @ts-ignore
      <ExchangeContent item={item} v-model={form.value}></ExchangeContent>
    ),
    confirmButtonText: '确认兑换',
    cancelButtonText: '再想想',
    showCancelButton: true,
    beforeClose: async (action, instance, done) => {
      if (action === 'cancel') return done()
      if (yabiData.value.currentValue < item.price * form.value.num)
        return push.error(
          `您的YA币不足,兑换所需${item.price * form.value.num}YA币,当前YA币${yabiData.value.currentValue}`,
        )
      try {
        instance.confirmButtonLoading = true
        await exchangeGoods(form.value)
        push.success('兑换成功')
        yabiStore.fetchYaBiData()
        item.stock -= form.value.num
        done()
      } catch (error) {
        console.log(error)
      } finally {
        instance.confirmButtonLoading = false
      }
    },
  })
}
</script>

<style>
.exchange-dialog {
  border-radius: 16px !important;
  width: 320px !important;
  overflow: hidden;
}

.exchange-dialog .el-message-box__header {
  padding: 20px 24px 0;
}

.exchange-dialog .el-message-box__title {
  font-size: 16px;
  font-weight: 600;
}

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

.exchange-dialog .el-message-box__btns {
  padding: 8px 24px 20px;
}

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

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

.exchange-dialog .el-message-box__btns .el-button:not(.el-button--primary) {
  border-radius: 8px;
  padding: 8px 28px;
}
</style>
