<template>
  <div class="fullPage">
    <div class="bg">
      <!-- 顶部导航 -->
      <GeneralHeader
        :showLanguageList="true"
        :title="$t('recharge')"
        color="black"
        style="box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); z-index: 999"
      />

      <!-- 主要内容 -->
      <div style="padding: 10px; display: flex; flex-direction: column; gap: 8px">
        <!-- 头部展示图 -->
        <img :src="imageUrl('headImg')" alt="" style="width: 100%" />

        <!-- 个人信息模块 -->
        <div style="display: flex; flex-direction: column; gap: 8px">
          <!-- 标题 -->
          <div style="display: flex; justify-content: space-between; align-items: center">
            <div style="font-weight: 600">{{ $t('my_information') }}</div>
            <div style="min-width: 0; width: 1.5em" @click="goGuide">
              <img
                src="../../assets/icon/Aslan/help.png"
                alt=""
                style="display: block; width: 100%; object-fit: cover"
              />
            </div>
          </div>

          <!-- 个人信息 -->
          <div
            style="
              min-width: 0;
              padding: 10px;
              border-radius: 8px;
              box-shadow: 0 0 4px 0 #00000050;

              display: flex;
              align-items: center;
              gap: 4px;
            "
          >
            <!-- 头像 -->
            <img
              :src="userInfo.userAvatar || ''"
              alt=""
              style="
                width: 3em;
                min-width: 0;

                border-radius: 50%;
                aspect-ratio: 1/1;
                object-fit: cover;
              "
              @error="handleAvatarImageError"
            />

            <!-- 基本信息 -->
            <div style="flex: 1; min-width: 0">
              <div style="display: flex; align-items: center; gap: 4px">
                <div
                  style="
                    font-weight: 700;

                    min-width: 0;

                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  "
                >
                  {{ userInfo.userNickname }}
                </div>

                <img
                  v-if="userInfo.isFreightAgent"
                  src="../../assets/icon/identity/coinSeller.png"
                  alt=""
                  style="
                    display: block;
                    width: auto;
                    min-width: 0;
                    height: 1.5em;
                    object-fit: contain;
                    flex-shrink: 0;
                  "
                />
              </div>
              <div style="font-weight: 500; color: rgba(0, 0, 0, 0.4)">
                {{ $t('user_id_prefix') }} {{ userInfo.account }}
              </div>
            </div>
          </div>
        </div>

        <!-- 商品展示模块 -->
        <div style="display: flex; flex-direction: column; gap: 8px">
          <!-- 当前选择国家 -->
          <div style="width: 100%; display: flex; justify-content: space-between">
            <div style="font-weight: 600">{{ $t('select_a_country') }}</div>
            <div
              style="
                padding: 4px;
                border-radius: 4px;
                background: #7726ff;
                box-shadow:
                  0 1px 18px 2px #f2d9ff inset,
                  0 1px 4px 2px #f2d9ff inset;

                display: flex;
                justify-content: center;
                align-items: center;
                gap: 4px;
              "
              @click="goMap"
            >
              <!-- 国旗 -->
              <img
                :src="selectedCountry.country?.nationalFlag"
                alt=""
                style="display: block; width: 1.5em; object-fit: contain"
              />

              <!-- 国家名字 -->
              <div style="font-size: 0.8em; font-weight: 500; color: #fff">
                {{ selectedCountry.countryName }}
              </div>
            </div>
          </div>

          <!-- 支付渠道 -->
          <div v-if="channels.length != 0" style="display: flex; flex-direction: column; gap: 12px">
            <div
              v-for="(channelItem, index) in channels"
              :key="index"
              style="
                padding: 10px;
                border-radius: 8px;
                box-shadow: 0 0 4px 0 #00000050;

                display: flex;
                flex-direction: column;
                gap: 8px;
              "
            >
              <!-- 支付类型 -->
              <div style="display: flex; align-items: center; gap: 8px">
                <img :src="channelItem.channel.channelIcon" style="display: block; width: 2.5em" />
                <div style="font-weight: 500">{{ channelItem.channel.channelName }}</div>
              </div>

              <!-- 支付商品 -->
              <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px">
                <div
                  style="
                    padding: 8px;
                    width: 100%;
                    border-radius: 8px;
                    box-shadow: 0 0 4px 0 #00000050;

                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    gap: 4px;
                  "
                  v-for="(goods, index) in commodityList"
                  :key="index"
                  @click="goPay(channelItem, goods)"
                >
                  <img
                    src="../../assets/icon/Aslan/coin.png"
                    alt=""
                    style="display: block; width: 3em; object-fit: cover"
                  />
                  <div style="font-size: 0.9em; font-weight: 500; color: #373232">
                    {{ goods.content }}
                  </div>
                  <div style="font-size: 1em; font-weight: 500; color: #131111">
                    ${{ goods.amountUsd }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { connectToApp } from '@/utils/appConnector.js'
import { goAirwallex } from '@/utils/payment'
import { showWarning } from '@/utils/toast.js'
import { handleAvatarImageError } from '@/utils/image/imageHandler.js'
import { preloadImages } from '@/utils/image/imagePreloader.js'

import { storeToRefs } from 'pinia'
import { useCountryStore } from '@/stores/country'
import { useTargetUser } from '@/stores/rechargeTarget'

import { getPngUrl } from '@/config/imagePaths.js'

import { searchPayRechargeUser } from '@/api/userInfo'
import { getPayAplication, getAppCommodityCard, payPlaceAnOrderRecharge } from '@/api/pay'

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

// 获取OSS图片URL的函数
const imageUrl = (filename) => getPngUrl('Recharge/', filename)

const countryStore = useCountryStore()
const targetUserStore = useTargetUser()
const route = useRoute()
const router = useRouter()

const applicationId = ref('1963531459019739137') //应用id
const regionId = ref('') //区域id
const type = ref(route.params.type || '') //第三方支付页面返回的类型

const { selectedCountry } = storeToRefs(countryStore) //国家信息
const userInfo = ref(targetUserStore.targetUser) //用户信息

const channels = ref([]) //支付渠道
const commodityList = ref([]) //商品列表

// 前往地图页
const goMap = () => {
  router.push({ path: '/map' })
}

// 前往引导页
const goGuide = () => {
  router.push({ path: '/recharge-guide' })
}

// 点击商品支付
const goPay = async (item, commodity) => {
  let payData = {
    applicationId: applicationId.value,
    payCountryId: selectedCountry.value.id,
    goodsId: commodity.id,
    userId: userInfo.value.id,
    channelCode: item.channel.channelCode,
  }

  const payRes = await payPlaceAnOrderRecharge(payData) // 下单充值
  if (!payRes.body) {
    console.log('Payment not available, please contact administrator!!!')
    return
  }
  if (payRes.body.factoryCode === 'AIRWALLEX') {
    targetUserStore.clearTargetUser() //清空目标用户信息
    // 拉起对应的h5支付页
    goAirwallex({
      result: payRes.body,
      props: {
        logoUrl: that.sysOriginLog,
        successUrl: `${location.origin}/#/pay-result?redirect=recharge&appType=${type.value}&appId=${applicationId.value}&appStatus=0`,
        failUrl: `${location.origin}/#/pay-result?redirect=recharge&appType=${type.value}&appId=${applicationId.value}&appStatus=1`,
      },
      callback: (response) => {
        if (response.code === 'FAIL') {
          showWarning('init fail!!!')
          return
        }
      },
    })
  }
  if (payRes.body.requestUrl) {
    location.href = decodeURIComponent(payRes.body.requestUrl)
  }
}

// 获取appCode
const getAppCode = async () => {
  const PayAplication = await getPayAplication(applicationId.value)
  return PayAplication.body.appCode
}

// 获取支付渠道和商品列表
const getPayAplicationAndCommodity = async () => {
  let appCommodityCardParams = {
    applicationId: applicationId.value,
    payCountryId: selectedCountry.value.id,
    regionId: regionId.value,
    type: userInfo.value.isSuperFreightAgent
      ? 'FREIGHT_GOLD_SUPER'
      : userInfo.value.isFreightAgent
        ? 'FREIGHT_GOLD'
        : 'GOLD',
  }
  const appCommodityCard = await getAppCommodityCard(appCommodityCardParams)
  commodityList.value = appCommodityCard.body.commodity
  if (appCommodityCard.body.channels) {
    channels.value = appCommodityCard.body.channels
  }
}

// 获取用户信息和国家列表
const getUserInfoAndCountry = async () => {
  let appCode = await getAppCode()
  if (appCode) {
    let params = {
      sysOrigin: appCode,
      account: userInfo.value.account,
      type: userInfo.value.isSuperFreightAgent
        ? 'FREIGHT_GOLD_SUPER'
        : userInfo.value.isFreightAgent
          ? 'FREIGHT_GOLD'
          : 'GOLD',
    }
    const countryAndRegionInfo = await searchPayRechargeUser(params)

    if (
      countryAndRegionInfo.body &&
      countryAndRegionInfo.body.regionId &&
      countryAndRegionInfo.body.countryList.length != 0
    ) {
      countryStore.setCountryList(countryAndRegionInfo.body.countryList) // 存储国家列表
      // 设置默认国家
      if (JSON.stringify(selectedCountry.value) == '{}') {
        countryStore.setCountry(countryAndRegionInfo.body.countryList[0])
      }

      regionId.value = countryAndRegionInfo.body.regionId //区域id
    }
  }
}

// 数据初始化
const init = async () => {
  await getUserInfoAndCountry() // 获取用户信息和国家列表
  await getPayAplicationAndCommodity() // 获取支付渠道和商品列表
}

// 使用工具函数连接APP
const connectToAppHandler = () => {
  connectToApp(async () => {
    // 连接成功回调
    await init() // 数据初始化
  })
}

// 预加载关键图片
const preloadCriticalImages = () => {
  const criticalImages = [imageUrl('headImg')]

  preloadImages(criticalImages)
}

onMounted(async () => {
  preloadCriticalImages() // 预加载关键图片
  connectToAppHandler()
})
</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;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}

.showGoodsList {
  display: block;
}

.hiddenGoodsList {
  display: none;
}

.extraList > div:not(:last-child) {
  border-bottom: 0.1px solid black;
}

.rotated {
  transform: rotate(90deg);
}

@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>
