<!-- 支付方式 -->
<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>
      <span class="font-size-15 ml-1">{{ unit }}</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>剩余点数：</span>
            <span style="color: var(--v-primary-base);">{{ accountBalance }}</span>
          </div>
          <div class="my-3" v-if="notEnoughMoney">
            <!-- <v-icon color="warning">mdi-information</v-icon> -->
            <!-- <span class="color-warning">{{ props.params?.txt || '当前余额不足，请选择其他支付方式' }}</span> -->
            <span class="color-error">
              当前剩余点数不足，<span class="text-decoration-underline cursor-pointer" @click="handleRecharge">去充值</span>
            </span>
          </div>
        </div>
        <!-- 二维码支付 -->
        <div v-if="isQrCodePay" style="text-align: center;">
          <QrCode :text="payQrCodeTxt" :width="170" style="margin: 0 auto;" />
          <div class="mb-5" v-if="payQrCodeTxt" style="color: var(--v-error-base);">扫码支付时请勿离开</div>
        </div>
        <!-- 钱包支付确认按钮 -->
        <div v-if="isWalletPay && !notEnoughMoney" class="mt-2" style="text-align: center;">
          <v-btn
            class="buttons" color="primary"
            :loading="payLoading"
            @click="walletPaySubmit"
          >
            确认
          </v-btn>
        </div>
      </div>
    </template>
  </v-card>

  <CtDialog :visible="showRecharge" :widthType="1" titleClass="text-h6" title="点数充值" :footer="false" submitText="确认" @close="handleRechargeClose">
    <Recharge @paySuccess="RechargePaySuccess"></Recharge>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'pay-index'})
import { computed, nextTick, 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'
import { rechargeOrderCreate } from '@/api/recruit/enterprise/member/points'
// import { payCalculation } from '@/utils/position'
import Recharge from '@/views/recruit/enterprise/memberCenter/myMembers/components/pointsAndBalance.vue'

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: ''
  },
  rechargeInfo: {
    type: Object,
    default: () => {}
  },
  appId: {
    type: Number,
    default: 10 // 10为一般情况下支付，11为充值支付
  },
  orderType: {
    type: Number,
    default: 2 // 订单类型 0平台订单| 1发布职位订单| 2发布众聘职位订单,示例值(1)
  },
  unit: {
    type: String,
    default: '点数'
  }
})

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

// 步骤：
//      1. 获取支付方式类型列表getCodeList (appId不同时数据返回有区别)
//      2. 创建支付订单（先获取有无创建的，没有就创建）getUnpaidOrderList (appId=11时只有创建，没有获取)
//      3. 如果是二维码类型支付（isQrCodePay=true）生成二维码（需要绑定支付订单的订单号）
//      4.轮询用户是否支付成功
//      如果是点数支付也要走上面的步骤，只是不生成二维码


const accountBalance = ref(0)

const notEnoughMoney = computed(() => {
  return (Number(props.cost) > Number(accountBalance.value))
})

// 生成二维码内容
const timer = ref(null)
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value); timer.value = null
})
// 如果是点数支付的话走完payOrderSubmit之后即扣点数，如果是二维码支付的话只是生成二维码，这一步以后是轮询是否支付成功
const paySubmit = async () => {
  if (!payType.value) return
  try {
    if (payOrder.value) {
      // 提交支付订单
      const params = {
        channelCode: payType.value, // 支付渠道
        // returnUrl: , // 支付成功后，支付渠道跳转回当前页；再由当前页，跳转回 {@link returnUrl} 对应的地址
      }
      if ((props.appId - 0) === 10) { // 众聘
        if (!payOrder.value?.id || !payOrder.value.notifyUrl) return
        params.id = payOrder.value.id // 支付单编号
        params.displayMode = payOrder.value.notifyUrl // 展示模式 notifyUrl
      }
      if ((props.appId - 0) === 11) { // 充值
        if (!payOrder.value?.payOrderId) return
        params.id = payOrder.value.payOrderId // 支付单编号
      }
      const res = await payOrderSubmit(params)
      payQrCodeTxt.value = res?.displayContent || '' // 二维码

      if (timer.value) clearInterval(timer.value); timer.value = null
      timer.value = setInterval(() => { payStatus() }, 1000) // 轮巡查询用户是否支付
      // if (isQrCodePay.value) {
      // }
    }
  } catch (error) {
    console.log(error)
  }
}

// 2.支付订单
const payOrder = ref({})
let maxCount = 0
const getUnpaidOrderList = async () => {
  try {
    if ((props.appId - 0) === 11) {
      //* 充值
      if (props.rechargeInfo.payPrice === undefined && props.rechargeInfo.packageId === undefined) return
      const params = {
        payPrice: (props.rechargeInfo.payPrice-0),
        packageId: props.rechargeInfo.id,
      }
      const data = await rechargeOrderCreate(params)
      payOrder.value = data || {}
    } else {
      //* 发布职位
      const data = await getUnpaidOrder({ spuId: props.spuId, type: props.orderType }) // 获取待支付的订单 (order:业务订单; payOrder:支付订单)
      if (!data) {
        // 订单超时，重新提交订单
        await createTradeOrder({
          spuId: props.spuId,
          spuName: props.spuName,
          price: props.cost,
          type:  props.orderType, // 发布众聘职位订单
        })
        if (maxCount > 3) return // 避免死循环
        maxCount++
        setTimeout(() => {
          getUnpaidOrderList()
        }, 1000)
      }
      // 
      payOrder.value = data?.payOrder || null
    }
    if (isQrCodePay.value) paySubmit() // 生成二维码内容
  } catch (error) {
    console.log(error)
  } finally {
    nextTick(() => {
      loading.value = false
    })
  }
}


// 1.支付方式
const isWalletPay = ref(false)
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)
  paySubmit() // 生成二维码内容
}
// 1.支付方式
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: props.appId})
      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)
        }
      })
    }
    getUnpaidOrderList()
  }
}
getCodeList()


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

// 钱包支付（余额支付）
const walletPaySubmit = () => {
  payLoading.value = true
  paySubmit() // 使用点数
}

import { useUserStore } from '@/store/user'; const store = useUserStore()
import Snackbar from '@/plugins/snackbar'
import { useRoute } from 'vue-router'; const route = useRoute()
import { useRouter } from 'vue-router'; const router = useRouter()
const payStatus = async () => {
  // if (timer.value) clearInterval(timer.value); timer.value = null
  // setTimeout(() => { // 测试代码
  // }, 2000)
  try {
    const data = await getOrderPayStatus({ id: (props.appId - 0) === 11 ? payOrder.value.payOrderId : payOrder.value.id })
    if ((data?.status - 0) === 10) {
      // 支付成功
      if (timer.value) clearInterval(timer.value); timer.value = null
      setTimeout(() => {
        // 更新点数(充值、发布职位)
        updateAccountInfo()
        // 支付成功
        emit('paySuccess')
        // 返回指定页面
        if (route.fullPath === props.returnUrl) router.go(0)
        else if (props.returnUrl) router.push(props.returnUrl)
        Snackbar.success('支付成功')
      }, 2000);
    }
  } catch (error) {
    console.log(error)
  }
}

const handleRechargeClose = () => {
  showRecharge.value = false
  loading.value = false
}

// 点数发生支付时点充值
const RechargePaySuccess = () => {
  showRecharge.value = false
  // updateAccountInfo()
}

const handleRecharge = () => {
  showRecharge.value = true
}

const updateAccountInfo = async (init = false) => {
  const account = await store.getEnterpriseUserAccountInfo()
  accountBalance.value = account?.balance
  if (init) return
  loading.value = false
}
if ((props.appId - 0) !== 11) updateAccountInfo(true) // 点数发生支付时点充值-充值不查余额

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