<!-- 支付方式 -->
<template>
  <v-card elevation="0" :loading="loading" :disabled="loading">
    <!-- 加载样式 -->
    <template v-slot:loader="{ isActive }">
      <v-progress-linear
        :active="isActive"
        color="var(--v-primary-base)"
        height="1"
        indeterminate
      ></v-progress-linear>
    </template>

    <!-- 赏金所需 -->
    <div class="pt-3 pb-5" style="color: var(--v-error-base); font-weight: bold; text-align: center;">
      <span class="font-size-13">￥</span>
      <span class="font-size-30">{{ cost }}</span>
    </div>
    <template v-if="payTypeList?.length">
      <v-chip-group v-model="payType" selected-class="text-primary" column mandatory @update:modelValue="payTypeChange">
        <v-chip filter v-for="k in payTypeList" :key="k.code" :value="k.code" class="mr-3" label>
          {{ k.name }}
          <svg-icon v-if="k.icon" class="ml-1" :name="k.icon" :size="k.size"></svg-icon>
        </v-chip>
      </v-chip-group>
      <div v-if="tip" style="text-align: center;" class="mt-2">{{ tip }}</div>
      <div>
        <!-- 支付 -->
        <div v-if="isWalletPay" class="py-10" style="text-align: center;">
          <div>
            <span >{{ $t('enterprise.account.accountBalances') }}：</span>
            <span style="color: var(--v-primary-base);">{{ balance }}</span>
          </div>
          <div class="my-3" v-if="balanceNotEnough">
            <!-- <v-icon color="warning">mdi-information</v-icon> -->
            <span class="color-warning">{{ props.params?.txt || '当前余额不足，请选择其他支付方式' }}</span>
          </div>
        </div>
        <div v-if="isQrCodePay" style="text-align: center;">
          <QrCode :text="payQrCodeTet" :width="170" style="margin: 0 auto;" />
          <div v-if="isQrCodePay && payQrCodeTet" style="color: var(--v-error-base);">扫码支付时请勿离开</div>
        </div>
        <div class="mt-2" style="text-align: center;">
          <!-- v-if="(isQrCodePay && payQrCodeTet) || isWalletPay" -->
          <v-btn
            v-if="isWalletPay && !balanceNotEnough"
            class="buttons" color="primary"
            :loading="payLoading"
            @click="walletPaySubmit"
          >
            <!-- {{ isWalletPay ? '确认' : '支付完成' }} -->
            确认
          </v-btn>
        </div>
      </div>
    </template>
  </v-card>
</template>

<script setup>
defineOptions({ name: 'pay-index'})
import { computed, onUnmounted, ref } from 'vue'
import QrCode from '@/components/QrCode'
import { definePayTypeList, qrCodePay, walletPay } from './until/payType'
import { getEnableCodeList, getUnpaidOrder, payOrderSubmit, getOrderPayStatus } from '@/api/common'
import { createTradeOrder } from '@/api/position'
import { useSharedState } from '@/store/sharedState'
const emit = defineEmits(['payTypeChange', 'paySuccess'])
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  cost: {
    type: [String, Number],
    default: 0
  },
  spuId: { // 原始数据id
    type: String,
    default: ''
  },
  spuName: {
    type: String,
    default: ''
  },
  returnUrl: {
    type: String,
    default: ''
  },
  type: {
    type: Number,
    default: 2 // 订单类型 0平台订单| 1发布职位订单| 2发布众聘职位订单,示例值(1)
  },
})

const loading = ref(true)
const tip = ref('')

const balance = JSON.parse(localStorage.getItem('enterpriseUserAccount'))?.balance || 0
const balanceNotEnough = computed(() => {
  return (Number(props.cost) > Number(balance))
})
// 支付方式
const isWalletPay = ref(true)
const isQrCodePay = ref(false)
const payTypeChange = (value) => {
  payType.value = value
  tip.value = payTypeList.value.find(e => e.code === payType.value)?.tip || ''
  isQrCodePay.value = qrCodePay.includes(payType.value)
  isWalletPay.value = walletPay.includes(payType.value)
  if (isQrCodePay.value) initPayQrCode() // 生成二维码内容
  emit('payTypeChange', value, balanceNotEnough)
}
// 支付方式
const payType = ref('')
const payTypeList = ref([])
const sharedState = useSharedState()
const codeList = ref(sharedState.payCodeList || [])
const getCodeList = async () => {
  try {
    if (!codeList.value?.length) {
      const list = await getEnableCodeList({appId: 10})
      codeList.value = list || []
      sharedState.setPayCodeList(codeList.value)
    } else {
      codeList.value = sharedState.payCodeList
    }
  } catch (error) {
    console.log(error)
  } finally {
    if (definePayTypeList?.length && codeList.value?.length) {
      codeList.value.forEach(code => {
        const item = definePayTypeList.find(p => p.code === code)
        if (item) {
          if (!payType.value) {
            tip.value = item.tip || ''
            payTypeChange(code) // 默认值赋值
          }
          payTypeList.value.push(item)
        }
      })
    }
  }
}
getCodeList()

const payOrder = ref({})
let maxCount = 0
const getUnpaidOrderList = async () => {
  try {
    const data = await getUnpaidOrder({ spuId: props.spuId, type: props.type }) // 获取待支付的订单
    // order:业务订单; payOrder:支付订单
    if (!data) {
      // 订单超时，重新提交订单
      await createTradeOrder({
        spuId: props.spuId,
        spuName: props.spuName,
        price: props.cost,
        type:  props.type, // 发布众聘职位订单
      })
      if (maxCount > 3) return // 避免死循环
      maxCount++
      setTimeout(() => {
        getUnpaidOrderList()
      }, 1000)
    }
    // 
    if (data?.payOrder) {
      payOrder.value = data.payOrder
      // loading.value = false
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}
getUnpaidOrderList() // getUnpaidOrder

const payLoading = ref(false)
const payQrCodeTet = ref('')

// 钱包支付（余额支付）
const walletPaySubmit = () => {
  // emit('paySubmit', payType.value)
}

// 生成二维码内容
const timer = ref(null)
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value); timer.value = null
})
const initPayQrCode = async () => {
  if (timer.value) clearInterval(timer.value); timer.value = null
  try {
    if (payOrder.value) {
      // 提交支付订单
      const params = {
        id: payOrder.value.id, // 支付单编号
        channelCode: payType.value, // 支付渠道
        displayMode: payOrder.value.notifyUrl, // 展示模式 notifyUrl
        // returnUrl: location.href, // 支付成功后，支付渠道跳转回当前页；再由当前页，跳转回 {@link returnUrl} 对应的地址
      }
      const res = await payOrderSubmit(params)
      payQrCodeTet.value = res?.displayContent || '' // 支付二维码
      timer.value = setInterval(() => { payStatus() }, 1000) // 轮巡查询用户是否支付
    }
  } catch (error) {
    console.log(error)
  }
}

import Snackbar from '@/plugins/snackbar'
import { useRouter } from 'vue-router'; const router = useRouter()
const payStatus = async () => {
  try {
    const data = await getOrderPayStatus({ id: payOrder.value.id })
    if ((data?.status - 0) === 10) {
      // 支付成功
      if (timer.value) clearInterval(timer.value); timer.value = null
      setTimeout(() => {
        if (props.returnUrl) router.push(props.returnUrl) // 返回指定页面
        else emit('paySuccess')
        Snackbar.success('付款成功')
      }, 1000);
    }
  } catch (error) {
    console.log(error)
  }
}

</script>
<style lang="scss" scoped>
.font-size-30 { font-size: 30px; }
</style>
