<script setup lang="ts">
import { fetchCreateEquityOrder, fetchGetEquityPayQrCode, fetchGetPayStatus } from '@/apis/equity'
import { useSystemLanguageStore } from '@/store/modules/system-language'
import { useUserStore } from '@/store/modules/user'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'

type VersionName = 'BasicVersion' | 'ProfessionalVersion' | 'FlagshipVersion' | 'EnterpriseVersion' | null

const currentSelectVersion = defineModel<VersionName>('currentSelectVersion', { required: true })

const { t } = useI18n()

const userStore = useUserStore()
const systemLanguageStore = useSystemLanguageStore()

const packageList = ref({
  ProfessionalVersion: {
    title: t('equity_module.professional_version'),
    list: [
      { name: t('equity_module.monthly_pass'), currentPrice: 19.9, originalPrice: 29.9, discountedPrice: 10 },
      { name: t('equity_module.annual_card'), currentPrice: 199, originalPrice: 238.9, discountedPrice: 39.9 },
    ],
  },
  FlagshipVersion: {
    title: t('equity_module.flagship_version'),
    list: [
      { name: t('equity_module.monthly_pass'), currentPrice: 29.9, originalPrice: 39.9, discountedPrice: 10 },
      { name: t('equity_module.annual_card'), currentPrice: 299, originalPrice: 358.9, discountedPrice: 59.9 },
    ],
  },
})
const currentSelectPackage = ref<0 | 1>(0)
const currentPaymentMethod = ref<'alipay' | 'wechatpay'>('alipay')
const isPaymentSuccess = ref(false)
const currentPayPrice = ref(0)
const payInfo = ref({
  url: '',
  payOrderSn: '',
})
const isPayQrcodeInvalid = ref(false)
let payStatusTimer: NodeJS.Timeout | null = null
let controller: AbortController | null = null

const isShowPayQrCode = computed(() => {
  return !!(
    currentSelectVersion.value && ['ProfessionalVersion', 'FlagshipVersion'].includes(currentSelectVersion.value)
  )
})

const currentPackageInfo = computed(() => {
  if (isShowPayQrCode.value) {
    return packageList.value[currentSelectVersion.value as 'ProfessionalVersion' | 'FlagshipVersion']
  }

  return null
})

const isEnglishLanguage = computed(() => systemLanguageStore.currentLanguageInfo.key === 'en')

watch(currentSelectVersion, (newVal) => {
  if ((!newVal && payStatusTimer !== null) || !isShowPayQrCode.value) {
    clearPayStatusTimer()
  }

  if (newVal && ['ProfessionalVersion', 'FlagshipVersion'].includes(newVal)) {
    getEquityPayQrCode()
  } else {
    clearPayStatusTimer()
  }

  clearPayInfo()

  currentSelectPackage.value = 0
  currentPaymentMethod.value = 'alipay'
})

watch(currentPackageInfo, (info) => {
  if (info) {
    currentPayPrice.value = info.list[0].currentPrice
  }
})

onMounted(() => {
  if (currentPackageInfo.value) {
    currentPayPrice.value = currentPackageInfo.value.list[0].currentPrice
  }
})

function clearPayInfo() {
  payInfo.value = {
    url: '',
    payOrderSn: '',
  }

  isPaymentSuccess.value = false
  isPayQrcodeInvalid.value = true
}

function getEquityPayQrCode() {
  controller && controller.abort()

  clearPayStatusTimer()
  clearPayInfo()

  controller = new AbortController()

  const payload = {
    type: '',
    domain: 'equity',
    validityUnit: '',
  }

  switch (currentSelectVersion.value) {
    case 'ProfessionalVersion':
      payload.type = 'professional'
      break
    case 'FlagshipVersion':
      payload.type = 'ultimate'
      break
  }

  switch (currentSelectPackage.value) {
    case 0:
      payload.validityUnit = 'month'
      break
    case 1:
      payload.validityUnit = 'year'
      break
  }

  fetchCreateEquityOrder<string>(payload, controller).then((orderRes) => {
    if (orderRes.code !== 0) return ''

    const payQrCodePayload = {
      payChannel: '',
      payOrderSn: orderRes.data,
    }

    switch (currentPaymentMethod.value) {
      case 'alipay':
        payQrCodePayload.payChannel = 'ALI_NATIVE'
        break
      case 'wechatpay':
        payQrCodePayload.payChannel = 'WX_NATIVE'
        break
    }

    fetchGetEquityPayQrCode<{ packageExtra: string; payOrderSn: string }>(payQrCodePayload, controller!).then(
      (qrcodeRes) => {
        if (orderRes.code !== 0) return ''

        isPayQrcodeInvalid.value = false

        payInfo.value = {
          url: qrcodeRes.data.packageExtra.replace('code_url=', ''),
          payOrderSn: qrcodeRes.data.payOrderSn,
        }

        /* 延迟自动取消支付查询 */
        setTimeout(
          () => {
            isPayQrcodeInvalid.value = true
          },
          10 * 60 * 1000,
        )

        getPayStatus()
      },
    )
  })
}

function getPayStatus() {
  function request() {
    fetchGetPayStatus<{ payStatus: 'Paid' | 'NoPayment' | 'Cancel' }>(payInfo.value.payOrderSn).then((res) => {
      if (res.code !== 0) return ''

      if (res.data.payStatus === 'Paid') {
        isPaymentSuccess.value = true
        clearPayStatusTimer()

        setTimeout(() => {
          currentSelectVersion.value = null

          userStore.fetchUpdateEquityInfo()
          window.$message.success(t('common_module.payment_success'))
        }, 1400)
      }
    })
  }

  clearPayStatusTimer()

  payStatusTimer = setInterval(() => {
    request()
  }, 1000)
}

function clearPayStatusTimer() {
  if (payStatusTimer !== null) {
    clearInterval(payStatusTimer)
    payStatusTimer = null
  }
}

function handlePaymentMethodSwitch(method: typeof currentPaymentMethod.value) {
  currentPaymentMethod.value = method

  getEquityPayQrCode()
}

function handlePackageSwitch(packageKey: typeof currentSelectPackage.value, price: number) {
  currentSelectPackage.value = packageKey

  currentPayPrice.value = price

  getEquityPayQrCode()
}

function handlePayQrCodeRefresh() {
  getEquityPayQrCode()
}
</script>

<template>
  <div v-if="isShowPayQrCode" class="px-[33px] pt-[33px]">
    <div>
      <h2 class="text-center text-[18px]">{{ currentPackageInfo?.title || '-' }}</h2>

      <ul v-if="currentPackageInfo" class="mt-[29px] flex">
        <li
          v-for="(packageItem, index) in currentPackageInfo.list"
          :key="packageItem.name"
          class="relative mr-[18px] h-[169px] flex-1 cursor-pointer select-none overflow-hidden rounded-[8px] border border-[#F4DEC5] bg-[#fff3e4] text-center transition-all"
          :class="currentSelectPackage === index ? 'border-[#FFC07B]' : ''"
          :style="
            currentSelectPackage === index ? 'background-image: linear-gradient(45deg, #FFD063, #FFF1D5, #FEBB57)' : ''
          "
          @click="handlePackageSwitch(index as 0 | 1, packageItem.currentPrice)"
        >
          <div
            class="font-600 mt-[22px] text-[16px] text-[#999]"
            :class="currentSelectPackage === index ? '!text-[#482801]' : ''"
          >
            {{ packageItem.name }}
          </div>

          <div class="font-600 mt-[20px] text-[20px] text-[#482801]">
            {{ packageItem.currentPrice }}<span class="text-[14px]"> ￥/{{ t('equity_module.month') }}</span>
          </div>

          <div
            v-show="currentSelectPackage === index"
            class="mt-[6px] text-center text-[14px] text-[#482801] line-through"
          >
            {{ packageItem.originalPrice }} ￥
          </div>

          <div
            v-show="currentSelectPackage !== index"
            class="absolute bottom-0 w-full bg-[#ffebd2] py-[6px] text-center text-[12px] text-[#9A5705]"
          >
            {{ t('equity_module.discounted') }}{{ packageItem.discountedPrice }}￥
          </div>

          <div
            v-show="currentSelectPackage === index"
            class="translate-1/2 absolute bottom-0 right-0 h-[60px] w-[60px] rotate-45 bg-[#ffac51]"
          >
            <i
              class="iconfont icon-queren absolute left-[2px] top-1/2 -translate-y-1/2 -rotate-45 text-[18px] text-white"
            ></i>
          </div>
        </li>
      </ul>
    </div>

    <div class="mt-[29px]">
      <div class="text-[14px]">{{ t('equity_module.payment_method') }}：</div>
      <ul class="mt-[12px] flex text-[14px]">
        <li
          class="mr-[12px] flex cursor-pointer items-center rounded-[5px] border border-[#999999] px-[16px] py-[6px] text-[14px] transition"
          :class="currentPaymentMethod === 'alipay' ? '!border-[#000DFF]' : ''"
          @click="handlePaymentMethodSwitch('alipay')"
        >
          <img class="mr-[5px] h-[16px] w-[16px]" src="@/assets/images/equity/alipay-icon.png" alt="alipay" />
          <span>{{ t('common_module.alipay') }}</span>
        </li>

        <li
          class="mr-[12px] flex cursor-pointer items-center rounded-[5px] border border-[#999999] px-[16px] py-[6px] text-[14px] text-[#333] transition"
          :class="currentPaymentMethod === 'wechatpay' ? '!border-[#000DFF]' : ''"
          @click="handlePaymentMethodSwitch('wechatpay')"
        >
          <img class="mr-[5px] h-[16px] w-[16px]" src="@/assets/images/equity/wechat-icon.png" alt="alipay" />
          <span>{{ t('common_module.wechat') }}</span>
        </li>
      </ul>
    </div>

    <div class="mt-[26px] flex justify-center">
      <template v-if="payInfo.url">
        <div v-if="currentPaymentMethod === 'wechatpay'" class="relative">
          <n-qr-code
            class="align-bottom"
            :class="isPayQrcodeInvalid ? 'blur-sm' : ''"
            :value="payInfo.url"
            :size="140"
            :padding="0"
          />
          <Transition name="mask">
            <div v-show="isPaymentSuccess" class="flex-center absolute inset-0 flex bg-[rgba(0,0,0,0.6)]">
              <div
                class="flex-center flex h-[50px] w-[50px] rounded-full border-[4px] border-solid border-[#fff] bg-[#52c41a]"
              >
                <i class="iconfont icon-queren font-600 text-[28px] text-white"></i>
              </div>
            </div>
          </Transition>

          <Transition name="mask">
            <div v-show="isPayQrcodeInvalid" class="flex-center absolute inset-0 flex">
              <div class="absolute inset-0 bg-[rgba(0,0,0,0.6)] blur-sm"></div>

              <i
                class="iconfont icon-huanyihuan font-600 z-1 relative cursor-pointer text-[30px] text-[#fff]"
                @click="handlePayQrCodeRefresh"
              ></i>
            </div>
          </Transition>
        </div>
        <div v-else-if="currentPaymentMethod === 'alipay'" class="flex-center flex">
          <iframe
            :src="payInfo.url"
            frameborder="0"
            width="140"
            height="140"
            class="object-center"
            scrolling="no"
          ></iframe>
        </div>
      </template>

      <div v-else class="flex-center flex h-[140px] w-[140px]">
        <n-spin size="large" />
      </div>
    </div>

    <div class="mt-[10px] flex items-center justify-center">
      <template v-if="currentPaymentMethod === 'alipay'">
        <img class="mr-[5px] mt-[6px] h-[16px] w-[16px]" src="@/assets/images/equity/alipay-icon.png" alt="alipay" />
        <span class="font-600 text-[16px]">
          {{ t('common_module.alipay') }} {{ t('equity_module.scan_code_payment') }}
          <span class="text-[24px] text-[#F25744]">{{ currentPayPrice }}</span
          >￥
        </span>
      </template>
      <template v-else-if="currentPaymentMethod === 'wechatpay'">
        <img class="mr-[5px] mt-[6px] h-[16px] w-[16px]" src="@/assets/images/equity/wechat-icon.png" alt="alipay" />
        <span class="font-600 text-[16px]">
          {{ t('common_module.wechat') }} {{ t('equity_module.scan_code_payment') }}
          <span class="text-[24px] text-[#F25744]">{{ currentPayPrice }}</span
          >￥
        </span>
      </template>
    </div>
  </div>

  <div v-if="currentSelectVersion === 'EnterpriseVersion'" class="flex-center flex h-full">
    <div class="flex flex-col items-center">
      <div class="flex">
        <img
          class="h-[42px] w-[42px] rounded-full object-cover"
          src="@/assets/images/equity/user-avatar.png"
          alt="Avatar"
        />

        <div class="ml-[11px] flex flex-col justify-between">
          <span class="font-600 text-[16px]">{{ t('equity_module.poc_products_professional_consultant') }}</span>
          <span class="font-600 text-[12px] text-[#999]">{{ t('equity_module.super_link_soft') }}</span>
        </div>
      </div>

      <div class="mt-[24px] flex justify-center px-[16px] text-start text-[14px] text-[#999]">
        {{ t('equity_module.for_details_please_scan_code_to_add_enterprise_wechat') }}
      </div>

      <img
        class="mt-[24px] h-[174px] w-[174px] object-cover"
        src="@/assets/images/equity/contact-qrcode.png"
        alt="QRcode"
      />

      <div class="flex-center mt-[30px] flex">
        <span
          class="inline-block border-t-[2px] border-dashed border-[#F5F5F5]"
          :class="isEnglishLanguage ? 'w-[30px]' : 'w-[60px]'"
        ></span>
        <span class="mx-[16px] text-[12px] text-[#999]">
          {{ t('equity_module.add_me_to_receive_the_following_benefits') }}
        </span>
        <span
          class="inline-block border-t-[2px] border-dashed border-[#F5F5F5]"
          :class="isEnglishLanguage ? 'w-[30px]' : 'w-[60px]'"
        ></span>
      </div>

      <ul class="mt-[29px] self-start px-[20px]">
        <li :class="isEnglishLanguage ? '' : 'flex items-center'">
          <div class="flex items-center">
            <div class="flex-center flex h-[26px] w-[26px] rounded-full bg-[#F2F4F7]">
              <img class="h-[16px] w-[16px] object-cover" src="@/assets/images/equity/consult.png" alt="consult" />
            </div>
            <span class="ml-[15px] text-[14px]">{{ t('equity_module.business_online_consulting') }}</span>
          </div>

          <div class="flex items-center" :class="isEnglishLanguage ? 'mt-[14px]' : 'ml-[25px]'">
            <div class="flex-center flex h-[26px] w-[26px] rounded-full bg-[#F2F4F7]">
              <img class="h-[16px] w-[16px] object-cover" src="@/assets/images/equity/programme.png" alt="programme" />
            </div>
            <span class="ml-[15px] text-[14px]">{{ t('equity_module.exclusive_customized_program') }}</span>
          </div>
        </li>

        <li class="mt-[14px]" :class="isEnglishLanguage ? '' : 'flex items-center'">
          <div class="flex items-center">
            <div class="flex-center flex h-[26px] w-[26px] rounded-full bg-[#F2F4F7]">
              <img class="h-[16px] w-[16px] object-cover" src="@/assets/images/equity/equity.png" alt="equity" />
            </div>
            <span class="ml-[15px] text-[14px]">{{ t('equity_module.exclusive_preferential_interest') }}</span>
          </div>

          <div class="flex items-center" :class="isEnglishLanguage ? 'mt-[14px]' : 'ml-[25px]'">
            <div class="flex-center flex h-[26px] w-[26px] rounded-full bg-[#F2F4F7]">
              <img class="h-[16px] w-[16px] object-cover" src="@/assets/images/equity/gift2.png" alt="gift" />
            </div>
            <span class="ml-[15px] text-[14px]">{{ t('equity_module.benefit_reminder') }}</span>
          </div>
        </li>
      </ul>
    </div>
  </div>

  <div v-show="!currentSelectVersion" class="flex-center flex h-full flex-col">
    <template v-if="userStore.equityInfo.equityLevel === 'normal'">
      <img
        class="h-[70px] w-[70px] object-contain"
        src="@/assets/images/equity/basic-version.png"
        alt="basic-version"
      />
      <div class="mt-[20px] text-[14px] text-[#333]">
        {{ t('equity_module.the_current_version_is_the_base_version') }}
      </div>
      <div class="mt-[10px] px-[20px] text-[14px] text-[#333]">
        {{ t('equity_module.more_benefits_can_be_upgraded_by_clicking_on_the_package') }}
      </div>
    </template>
    <template
      v-else-if="userStore.equityInfo.equityLevel === 'professional' || userStore.equityInfo.equityLevel === 'ultimate'"
    >
      <img
        class="h-[70px] w-[70px] object-contain"
        src="@/assets/images/equity/professional-version.png"
        alt="basic-version"
      />
      <div class="mt-[20px] text-[14px] text-[#333]">
        {{
          userStore.equityInfo.equityLevel === 'professional'
            ? t('equity_module.the_current_version_is_the_professional_version')
            : t('equity_module.the_current_version_is_the_flagship_version')
        }}
      </div>
      <div class="mt-[10px] px-[20px] text-[14px] text-[#333]">
        {{ t('equity_module.more_benefits_can_be_upgraded_by_clicking_on_the_package') }}
      </div>
    </template>
  </div>
</template>
