<!-- 支付方式 -->
<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>
    <radioGroupUI
      :modelValue="payType"
      :item="payTypeItem"
      @change="val => payTypeChange(val)"
    ></radioGroupUI>
    <div class="pa-5">
      <!-- 支付 -->
      <div v-if="isWalletPay">
        <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-10" style="text-align: center;">
        <!-- v-if="(isQrCodePay && payQrCodeTet) || isWalletPay" -->
        <v-btn
          v-if="isWalletPay"
          class="buttons" color="primary"
          :loading="payLoading"
          @click="paySubmit"
        >
          <!-- {{ isWalletPay ? '确认' : '支付完成' }} -->
          确认
        </v-btn>
      </div>
    </div>
  </v-card>
</template>

<script setup>
defineOptions({ name: 'pay-index'})
import { computed, onUnmounted, ref } from 'vue'
import radioGroupUI from '@/components/FormUI/radioGroup'
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', ])
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  cost: {
    type: [String, Number],
    default: 0
  },
  spuId: { // 原始数据id
    type: String,
    default: ''
  },
  spuName: {
    type: String,
    default: ''
  },
  type: {
    type: Number,
    default: 2 // 订单类型 0平台订单| 1发布职位订单| 2发布众聘职位订单,示例值(1)
  },
})
const loading = ref(true)

// 支付方式
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) {
            // payType.value = code
            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:支付订单
    console.log('获取待支付的订单', data)
    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)
  }
}
getUnpaidOrderList() // getUnpaidOrder

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

const payTypeItem = {
  label: '',
  width: 1,
  hideDetails: true,
  itemText: 'name',
  itemValue: 'code',
  items: payTypeList.value
}

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 = (val) => {
  payType.value = val
  isQrCodePay.value = qrCodePay.includes(payType.value)
  isWalletPay.value = walletPay.includes(payType.value)
  if (isQrCodePay.value) initPayQrCode() // 生成二维码内容
  emit('payTypeChange', val, balanceNotEnough)
}

const paySubmit = () => {
  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: '',
      }
      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) === 1) {
      // 支付成功
      if (timer.value) clearInterval(timer.value); timer.value = null
      const query = { hire: true }
      router.push({ path: '/recruit/enterprise/position', query }) // 返回到众聘页面
      setTimeout(() => {
        Snackbar.success('付款成功')
      }, 1000);
    }
  } catch (error) {
    console.log(error)
  }
}

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