<template>
  <div class="distribution-page">
    <div class="bg">
      <GeneralHeader
        :showLanguageList="true"
        :title="t('item_distribution')"
        color="black"
        style="box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); z-index: 999"
      />

      <main class="distribution-content">
        <div class="tabs">
          <div
            v-for="(item, index) in tabList"
            :key="index"
            class="tab-item"
            :class="activeIndex == index ? 'tabName-active' : 'tabName'"
            ref="tabItems"
            v-touch-tap="() => setActiveTab(index)"
          >
            {{ t(item.name) }}
          </div>
          <div class="tab-underline" :style="underlineStyle"></div>
        </div>

        <div class="product-grid">
          <div
            v-for="(product, index) in productList"
            :key="index"
            class="product-card"
            v-touch-tap="() => showSendDialog(product)"
          >
            <img :src="product.cover" alt="" class="product-cover" />
            <button class="send-pill" type="button">
              {{ t('send') }}
            </button>
          </div>
        </div>

        <maskLayer :maskLayerShow="dialogshow" @close="closedPopup">
          <div class="send-dialog" @touchend.stop @pointerup.stop>
            <img :src="selectedGoods.cover" alt="" class="dialog-cover" />
            <div class="validity-row">
              <span>{{ t('validity') }}:</span>
              <strong>{{ validityPeriod }}{{ t('day') }}</strong>
            </div>
            <div class="send-form">
              <input
                type="text"
                :placeholder="t('enter_user_id_placeholder')"
                class="user-input"
                v-model="targetUserId"
              />
              <button
                class="confirm-btn"
                type="button"
                :style="{ backgroundColor: confirmClick ? '#bb92ff' : '#00000080' }"
                v-touch-tap="sendGoods"
              >
                {{ t('confirm') }}
              </button>
            </div>
          </div>
        </maskLayer>
      </main>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { showWarning, showSuccess } from '@/utils/toast.js'
import { useI18n } from 'vue-i18n'

import { getAdminCenterList, giveProps, hasSendGiftsPermission } from '@/api/itemDistribution'
import { searchUser } from '@/api/userInfo'

import GeneralHeader from '@/components/GeneralHeader.vue'
import maskLayer from '@/components/MaskLayer.vue'

const { t, locale } = useI18n()

const tabList = ref([
  {
    id: 1,
    name: 'frames',
  },
  {
    id: 2,
    name: 'vehicles',
  },
  // {
  //   id: 3,
  //   name: 'chat_box',
  // },
  // {
  //   id: 4,
  //   name: 'theme',
  // },
])

const activeIndex = ref(0)
const currentTab = ref('frames') //选中名字
const tabItems = ref([]) // 存储标签DOM引用

const confirmClick = ref(true)

// 选择标签
const setActiveTab = (index) => {
  if (activeIndex.value != index) {
    console.log('切换标签')
    productList.value = [] //置空商品列表
    activeIndex.value = index
    currentTab.value = tabList.value[index].name

    loadProps()
  }
}

// 计算下划线样式
const underlineStyle = computed(() => {
  console.log('计算属性')

  // 访问 locale.value 使其成为依赖项
  const currentLocale = locale.value
  console.log('当前语言:', currentLocale)

  if (tabItems.value.length === 0) return {} //没有这个元素
  const activeTab = tabItems.value[activeIndex.value]
  const underlineWidth = 24
  console.log('选中元素的左边距', activeTab.offsetLeft)

  return {
    position: 'absolute',
    left: `${activeTab.offsetLeft + activeTab.offsetWidth / 2 - underlineWidth / 2}px`,
    bottom: '0',
    transition: 'left 0.3s ease', // 平滑过渡
  }
})

const targetUserId = ref('')

// 检查是否有赠送某个栏目商品的资格
const getHasSendVIPPermission = async (propsType) => {
  const response = await hasSendGiftsPermission(propsType)
  console.log('response:', response)
  return response.body
}

const sendGoods = async () => {
  if (confirmClick.value) {
    confirmClick.value = false

    console.log('赠送用户id：', targetUserId.value)
    console.log('赠送商品：', selectedGoods.value)

    try {
      const targetUserInfo = await searchUser(targetUserId.value)
      console.log('targetUserInfo:', targetUserInfo)
      if (targetUserInfo.status && targetUserInfo.body) {
        const data = {
          propsId: selectedGoods.value.id,
          acceptUserId: targetUserInfo.body.id,
        }
        const res = await giveProps(data)
        if (res.errorCode == 0 && res.status) {
          closedPopup()
          showSuccess(t('gift_delivery_successful'))
        } else {
          confirmClick.value = true
        }
      } else {
        confirmClick.value = true
      }
    } catch (error) {
      console.log('error:', error)
      // 信息提示id有误
      showWarning(error.response.errorMsg)
      confirmClick.value = true
      throw error
    }
  }
}

// 选中的标签
const getPropsType = () => {
  const typeMap = {
    frames: 'AVATAR_FRAME',
    vehicles: 'RIDE',
    chat_box: 'CHAT_BUBBLE',
    theme: 'THEME',
    vip: 'NOBLE_VIP',
  }
  return typeMap[currentTab.value]
}

// 获取商品列表
const loadProps = async () => {
  try {
    const params = {
      propsType: getPropsType(),
      currencyType: 'GOLD',
    }
    const response = await getAdminCenterList(params)
    console.log('response:', response)
    productList.value = response.body
  } catch (error) {
    throw error
  }
}

// 虚拟商品数据
const productList = ref([])

// 选中商品
const selectedGoods = ref({})

const validityPeriod = computed(() => {
  return currentTab.value == 'VIP' ? '3' : '7'
})

// 获取本地图片
const getImageUrl = (imgUrl) => {
  return new URL(imgUrl, import.meta.url).href
}

const dialogshow = ref(false)
// 展示弹窗
const showSendDialog = (product) => {
  console.log('product:', product)
  selectedGoods.value = product
  dialogshow.value = true
}

// 关闭弹窗
const closedPopup = () => {
  confirmClick.value = true
  selectedGoods.value = {}
  targetUserId.value = ''
  dialogshow.value = false
}

onMounted(() => {
  console.log('onMounted')

  // 检查是否有赠送VIP的资格
  if (getHasSendVIPPermission('NOBLE_VIP')) {
    tabList.value.push({
      id: 3,
      name: 'vip',
    })
  }

  if (tabItems.value.length > 0) {
    underlineStyle.value // 触发计算属性更新
  }
  loadProps()
})
</script>

<style scoped>
* {
  color: black;
  box-sizing: border-box;
}

.distribution-page {
  background-color: #f5f7fb;
  height: 100vh;
  position: relative;
  overflow-y: auto;
}

.distribution-page::-webkit-scrollbar {
  display: none;
}

.bg {
  width: 100vw;
  min-height: 100vh;
  background-image: url(../../assets/images/Aslan/secondBg.png);
  background-size: 100% auto;
  background-repeat: no-repeat;
}

.distribution-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 14px 14px 28px;
}

.tabs {
  display: flex;
  justify-content: space-around;
  position: relative;
  padding: 6px;
  border-radius: 18px;
  background: rgba(255, 255, 255, 0.86);
  box-shadow: 0 10px 26px rgba(37, 45, 65, 0.07);
}

.tab-item {
  flex: 1;
  min-height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 8px;
  font-size: 1.1em;
  font-weight: 800;
  text-align: center;
  border-radius: 14px;
  touch-action: manipulation;
}

.tabName {
  color: rgba(31, 41, 55, 0.48);
}

.tabName-active {
  color: #111827;
  background: #f4f2ff;
}

.tab-underline {
  width: 24px;
  height: 4px;
  border-radius: 999px;
  background-color: #bb92ff;
}

.product-grid {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 14px;
}

.product-card {
  min-width: 0;
  min-height: 170px;
  padding: 14px 10px 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  border: 1px solid rgba(212, 218, 232, 0.9);
  border-radius: 18px;
  background-color: rgba(255, 255, 255, 0.96);
  box-shadow: 0 10px 26px rgba(37, 45, 65, 0.08);
  touch-action: manipulation;
}

.product-cover {
  display: block;
  width: 68%;
  max-height: 112px;
  object-fit: contain;
}

.send-pill,
.confirm-btn {
  border: 0;
  color: white;
  background-color: #bb92ff;
  font-weight: 800;
  touch-action: manipulation;
}

.send-pill {
  min-width: 76px;
  min-height: 36px;
  padding: 8px 14px;
  border-radius: 999px;
  font-size: 1em;
}

.send-dialog {
  margin: 18vh 5% 0;
  padding: 22px 18px;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-radius: 22px;
  box-shadow: 0 18px 45px rgba(0, 0, 0, 0.18);
}

.dialog-cover {
  display: block;
  width: 62%;
  max-height: 190px;
  object-fit: contain;
}

.validity-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 14px 0;
  font-size: 1.08em;
  font-weight: 700;
}

.validity-row span {
  color: rgba(0, 0, 0, 0.5);
}

.validity-row strong {
  color: #000;
}

.send-form {
  width: 100%;
  display: flex;
  align-items: stretch;
  gap: 10px;
}

.user-input {
  flex: 1;
  min-width: 0;
  border-radius: 12px;
  border: 0;
  outline: none;
  background-color: #f1f1f1b2;
  padding: 12px;
  font-size: 1.05em;
  font-weight: 700;
}

.confirm-btn {
  min-width: 86px;
  border-radius: 12px;
  padding: 0 14px;
  font-size: 1.05em;
}

.product-card:active,
.send-pill:active,
.confirm-btn:active,
.tab-item:active {
  transform: scale(0.98);
}

@media screen and (max-width: 360px) {
  * {
    font-size: 12px;
  }
}

@media screen and (min-width: 360px) {
  * {
    font-size: 14px;
  }
}

@media screen and (min-width: 768px) {
  * {
    font-size: 24px;
  }
}

@media screen and (min-width: 1024px) {
  * {
    font-size: 32px;
  }
}
</style>
