<template>
  <div class="fullPage">
    <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"
      />

      <!-- 标签 -->
      <div
        style="
          display: flex;
          justify-content: space-around;

          background-color: transparent;
          position: relative;
        "
      >
        <div
          v-for="(item, index) in tabList"
          :key="index"
          style="font-size: 1.3em; padding: 10px 0; flex: 1; text-align: center"
          class="tab-item"
          :class="activeIndex == index ? 'tabName-active' : 'tabName'"
          ref="tabItems"
          @click="setActiveTab(index)"
        >
          {{ t(item.name) }}
        </div>
        <!-- 下划线元素 -->
        <div
          v-show="tabList.length > 0"
          style="width: 15px; height: 3px; background-color: #bb92ff"
          :style="underlineStyle"
        ></div>
      </div>

      <!-- 商品列表 -->
      <div
        style="
          width: 100%;
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 12px;
          padding: 15px;
        "
      >
        <div v-for="(product, index) in productList" :key="index" @click="showSendDialog(product)">
          <div
            style="
              background-color: white;
              border-radius: 10px;
              box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.2);
              display: flex;
              flex-direction: column;
              align-items: center;
            "
          >
            <img :src="product.cover" alt="" style="width: 60%; margin: 10px 0" />
            <button
              style="
                background-color: #bb92ff;
                color: white;
                margin-bottom: 10px;
                border: 0;
                border-radius: 20px;
                padding: 5px 10px;
              "
            >
              {{ t('send') }}
            </button>
          </div>
        </div>
      </div>

      <!-- 弹窗 -->
      <!-- 遮罩层 -->
      <maskLayer :maskLayerShow="dialogshow" @click="closedPopup">
        <div
          style="
            padding: 20px;
            background-color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            border-radius: 20px;
            margin: 20% 5%;
          "
          @click.stop
        >
          <img :src="selectedGoods.cover" alt="" style="width: 60%; margin: 5px 0" />
          <div style="font-weight: 600; margin: 10px 0">
            <span style="color: #00000080; margin-right: 10px">{{ t('validity') }}:</span>
            <span style="font-weight: 700; color: #000">3{{ t('day') }}</span>
          </div>
          <div
            style="
              width: 90%;
              display: flex;
              justify-content: center;
              align-items: center;
              gap: 4px;
            "
          >
            <input
              type="text"
              :placeholder="t('enter_user_id_placeholder')"
              style="
                flex: 1;
                min-width: 0;
                align-self: stretch;

                border-radius: 8px;
                border: 0;
                outline: none;
                background-color: #f1f1f1b2;
                padding: 8px;
                margin-right: 4px;
                font-size: 1em;
                font-weight: 590;
              "
              v-model="targetUserId"
            />
            <button
              style="
                width: auto;
                min-width: 0;
                align-self: stretch;

                border-radius: 8px;
                border: 0;
                padding: 8px;
                color: white;
                font-size: 1em;
                font-weight: 590;
              "
              :style="{ backgroundColor: confirmClick ? '#bb92ff' : '#00000080' }"
              @click="sendGoods"
            >
              {{ t('confirm') }}
            </button>
          </div>
        </div>
      </maskLayer>
    </div>
  </div>
</template>

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

import {
  getSendGiftsPermissionList,
  getBDPropsList,
  giveProps,
  hasSendGiftsPermission,
} from '@/api/bdCenter'
import { searchUser } from '@/api/userInfo'

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

const { t, locale } = useI18n()

const tabList = ref([])

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]
  console.log('选中元素的左边距', activeTab.offsetLeft)

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

const targetUserId = ref('')

// 获取赠送礼物的类型列表
const getSendGiftsPermissions = async () => {
  const response = await getSendGiftsPermissionList()
  console.log('response:', response)

  const permissions = response.body

  const tabs = []
  const hasVip = permissions.some((p) => p.startsWith('NOBLE_VIP'))

  if (permissions.includes('AVATAR_FRAME')) {
    tabs.push({ id: 1, name: 'frames' })
  }
  if (permissions.includes('RIDE')) {
    tabs.push({ id: 2, name: 'vehicles' })
  }
  if (hasVip) {
    tabs.push({ id: 3, name: 'vip' })
  }

  tabList.value = tabs

  if (tabs.length > 0) {
    activeIndex.value = 0
    currentTab.value = tabs[0].name
  }

  return tabs
}

// 赠送礼物
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',
    vip: 'NOBLE_VIP',
  }
  return typeMap[currentTab.value]
}

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

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

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

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(async () => {
  console.log('onMounted')
  await getSendGiftsPermissions()

  if (tabItems.value.length > 0) {
    underlineStyle.value
  }

  if (tabList.value.length > 0) {
    loadProps()
  }
})
</script>

<style scoped>
* {
  color: black;
}

.fullPage {
  background-color: #ffffff;
  min-height: 100vh;
  position: relative;
}

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

.tabName {
  color: #00000066;
}

.tabName-active {
  color: black;
  font-weight: 500;
}

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

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

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

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