<template>
  <div class="fullPage">
    <div class="bg">
      <!-- 顶部 -->
      <MobileHeader title="Recharge">
        <template v-slot:extraFunction>
          <div
            style="
              display: flex;
              align-items: center;
              position: relative;
              color: rgba(187, 146, 255, 1) !important;
            "
            @click="listBt"
          >
            <div style="font-weight: bold">{{ selectedLanguage.type }}</div>
            <div
              style="margin-left: 5px; transition: transform 0.5s"
              :class="{ rotated: visibleList }"
            >
              >
            </div>
            <transition name="slide-fade">
              <div
                style="
                  position: absolute;
                  right: 0;
                  top: 100%;
                  padding: 10px;
                  display: flex;
                  flex-direction: column;
                  width: max-content;
                  background-color: rgba(255, 255, 255, 0.1);
                  border-radius: 10px;
                  margin-top: 5px;
                  backdrop-filter: blur(8px);
                "
                v-show="visibleList"
                class="extraList"
              >
                <div
                  style="padding: 8px; color: white !important; font-weight: 590"
                  v-for="(item, index) in languageList"
                  :key="index"
                >
                  {{ item.type }}
                </div>
              </div>
            </transition>
          </div>
        </template>
      </MobileHeader>

      <div style="padding: 10px">
        <!-- 头部展示图 -->
        <img src="../assets/images/firstRechargeBonus.png" alt="" style="width: 100%" />

        <div style="font-weight: 600; margin-bottom: 10px">Recharge ID：</div>
        <!-- 个人信息 -->
        <div
          style="
            display: flex;
            border-radius: 8px;
            box-shadow: 0 0 4px 0 #00000050;
            align-items: center;
          "
        >
          <img
            :src="userProfile.userAvatar"
            alt=""
            style="
              width: 10%;
              margin: 10px;
              border-radius: 50%;
              aspect-ratio: 1/1;
              object-fit: cover;
            "
          />
          <div style="">
            <div style="font-weight: 700; display: flex; align-items: center">
              {{ userProfile.userNickname }}
              <img src="../assets/icon/RA.png" alt="" style="height: 20px; margin-left: 5px" />
            </div>
            <div style="font-weight: 500; color: rgba(0, 0, 0, 0.4)">ID:{{ userProfile.id }}</div>
          </div>
        </div>

        <div style="width: 100%; display: flex; justify-content: space-between; margin: 10px 0">
          <div style="font-weight: 600">Select a country：</div>
          <div style="font-weight: 500; color: rgba(0, 0, 0, 0.4)" @click="goMap">
            <img src="../assets/icon/Vector.png" alt="" style="width: 10px" />
            {{ selectedCountry.countryName }}
          </div>
        </div>

        <!-- 支付渠道 -->
        <div v-if="channels.length != 0">
          <div v-for="(channelItem, index) in channels" :key="index">
            <!-- 支付类型 -->
            <div
              style="
                display: flex;
                border-radius: 8px;
                box-shadow: 0 0 4px 0 #00000050;
                align-items: center;
              "
              @click="setChannelName(channelItem.channel.channelName)"
            >
              <img :src="channelItem.channel.channelIcon" alt="" style="width: 10%; margin: 10px" />
              <div style="font-weight: 500">{{ channelItem.channel.channelName }}</div>
            </div>

            <!-- 支付商品 -->
            <div
              style="
                border-radius: 8px;
                box-shadow: 0 0 4px 0 #00000050;
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 12px;
                padding: 10px;
                margin-top: 1rem;
              "
              v-if="selectedChannelName == channelItem.channel.channelName"
            >
              <div
                style="
                  width: 100%;
                  border-radius: 8px;
                  box-shadow: 0 0 4px 0 #00000050;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                "
                v-for="(goods, index) in commodityList"
                :key="index"
                @click="goPay(channelItem, goods)"
              >
                <img src="../assets/icon/coin.png" alt="" style="width: 30%" />
                <div>{{ goods.content }}</div>
                <div>${{ goods.amountUsd }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import MobileHeader from '../components/MobileHeader.vue'
import { searchUser, searchPayRechargeUser } from '@/api/userInfo'
// import { getUserIdentity } from "@/api/wallet";
import { getPayAplication, getAppCommodityCard, payPlaceAnOrderRecharge } from '@/api/pay'
import { goAirwallex } from '@/utils/payment'
import { showError, showWarning, showInfo, showSuccess } from '@/utils/toast.js'

import { useRoute } from 'vue-router'
import router from '@/router'
import { useCountryStore } from '@/stores/country'
import { storeToRefs } from 'pinia'

const countryStore = useCountryStore()
const route = useRoute()

const languageList = ref([
  {
    type: 'English',
  },
])
const selectedLanguage = ref({
  type: 'English',
})
const visibleList = ref(false)
const listBt = () => {
  visibleList.value = !visibleList.value
}

const applicationId = ref('1963531459019739137')
const userProfile = ref({}) //用户信息
const type = ref('') //用户身份

const regionId = ref('') //区域id

const { list: countryList, selectedCountry } = storeToRefs(countryStore) //国家信息

const channels = ref([]) //支付渠道
const selectedChannelName = ref('') //选中的支付渠道

const commodityList = ref([]) //商品列表
const selectedCommodity = ref({}) //选中的商品

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

const goPay = async (item, commodity) => {
  selectedCommodity.value = commodity
  let payData = {
    applicationId: applicationId.value,
    payCountryId: selectedCountry.value.id,
    goodsId: commodity.id,
    userId: userProfile.value.id,
    channelCode: item.channel.channelCode,
  }
  console.log('payData:', payData)

  const payRes = await payPlaceAnOrderRecharge(payData)
  const body = payRes.body
  if (!body) {
    console.log('Payment not available, please contact administrator!!!')
    return
  }
  if (body.factoryCode === 'AIRWALLEX') {
    goAirwallex({
      result: 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 (body.requestUrl) {
    location.href = decodeURIComponent(body.requestUrl)
  }
}

// 选中支付渠道
const setChannelName = (channelName) => {
  selectedChannelName.value = selectedChannelName.value != channelName ? channelName : ''
}

onMounted(async () => {
  type.value = route.params.type || 'GOLD'

  const PayAplication = await getPayAplication(applicationId.value)
  console.log('PayAplication:', PayAplication)
  if (PayAplication.body && PayAplication.body.appCode) {
    let params = {
      sysOrigin: PayAplication.body.appCode,
      account: route.query.targetUserId,
      type:
        route.query.isSuperFreightAgent === 'true'
          ? 'FREIGHT_GOLD_SUPER'
          : route.query.isFreightAgent === 'true'
          ? 'FREIGHT_GOLD'
          : 'GOLD',
    }
    const userInfo = await searchPayRechargeUser(params)

    if (userInfo.body && userInfo.body.regionId && userInfo.body.countryList.length != 0) {
      userProfile.value = { ...userInfo.body.userProfile, type: 'GOLD' }

      countryStore.setCountryList(userInfo.body.countryList)
      if (JSON.stringify(selectedCountry.value) == '{}') {
        countryStore.setCountry(userInfo.body.countryList[0])
      }

      regionId.value = userInfo.body.regionId

      let appCommodityCardParams = {
        applicationId: applicationId.value,
        payCountryId: selectedCountry.value.id,
        regionId: userInfo.body.regionId,
        type:
          route.query.isSuperFreightAgent === 'true'
            ? 'FREIGHT_GOLD_SUPER'
            : route.query.isFreightAgent === 'true'
            ? 'FREIGHT_GOLD'
            : 'GOLD',
      }
      const appCommodityCard = await getAppCommodityCard(appCommodityCardParams)
      console.log('appCommodityCard:', appCommodityCard)
      commodityList.value = appCommodityCard.body.commodity
      if (appCommodityCard.body.channels) {
        channels.value = appCommodityCard.body.channels
      }
    }
  }
})

watch(selectedCountry, (New, Old) => {
  console.log(`新值：${New.id},旧值：${Old.id}`)
})
</script>

<style scoped>
* {
  color: black;
  font-family: 'SF Pro';
}

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

.bg {
  width: 100vw;
  min-height: 100vh;
  background-image: url(../assets/images/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);
}
</style>
