<template>
  <div>
    <div class="flex gap-6">
      <!-- 左侧：商品列表区域 -->
      <div class="flex-1 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 gap-4">
              <div
                v-for="item in virtualGoodsList"
                :key="item.id"
                class="group bg-white rounded-lg p-4 flex flex-col items-center shadow-md transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-300"
                @click="onExchangeGoods(item)"
              >
                <div
                  class="w-20 h-20 mb-3 flex items-center justify-center bg-blue-50/50 rounded-lg p-2"
                >
                  <img
                    :src="item.imageUrl"
                    alt=""
                    class="rounded-lg w-full h-full object-contain"
                  />
                </div>
                <div
                  class="text-sm text-gray-700 mb-3 font-medium text-center line-clamp-2 min-h-[40px]"
                >
                  {{ item.name }}
                </div>
                <div class="bg-blue-600 text-white text-xs px-4 py-1.5 rounded font-medium">
                  {{ item.price }} 积分
                </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 gap-4">
              <div
                v-for="item in realGoodsList"
                :key="item.id"
                class="group bg-white rounded-lg p-4 flex flex-col items-center shadow-md transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-300"
                @click="onExchangeGoods(item)"
              >
                <div
                  class="w-20 h-20 mb-3 flex items-center justify-center bg-blue-50/50 rounded-lg p-2"
                >
                  <img
                    :src="item.imageUrl"
                    alt=""
                    class="rounded-lg w-full h-full object-contain"
                  />
                </div>
                <div
                  class="text-sm text-gray-700 mb-3 font-medium text-center line-clamp-2 min-h-[40px]"
                >
                  {{ item.name }}
                </div>
                <div class="bg-blue-600 text-white text-xs px-4 py-1.5 rounded font-medium">
                  {{ item.price }} 积分
                </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="w-80 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"
            >
              {{ currentYaBi }}
            </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, getYaBiData } 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'
const activeTab = ref('深圳')
const tabs = ref(regionListOptions)

const currentYaBi = ref(0)
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()
}

// 获取YA币数据
const getYaBiDataFn = async () => {
  const { data } = await getYaBiData()
  currentYaBi.value = data.currentValue
}

// 兑换商品

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币兑换',
    customStyle: {
      width: '1000px',
    },
    message: () => (
      // @ts-ignore
      <ExchangeContent item={item} v-model={form.value}></ExchangeContent>
    ),
    confirmButtonText: '确认兑换',
    cancelButtonText: '取消',
    showCancelButton: true,
    center: true,
    beforeClose: async (action, instance, done) => {
      if (action === 'cancel') return done()
      if (currentYaBi.value < item.price * form.value.num)
        return ElMessage.error(
          `您的YA币不足,兑换所需${item.price * form.value.num}YA币,当前YA币${currentYaBi.value}`,
        )
      try {
        instance.confirmButtonLoading = true
        await exchangeGoods(form.value)
        ElMessage.success('兑换成功')
        getYaBiDataFn()
        done()
      } catch (error) {
        console.log(error)
      } finally {
        instance.confirmButtonLoading = false
      }
    },
  })
}

onMounted(async () => {
  getYaBiDataFn()
})
</script>
