<script setup lang="ts">
import { post } from '@af-mobile-client-vue3/services/restTools'
import useUserStore from '@af-mobile-client-vue3/stores/modules/user'
import {
  showDialog,
  showToast,
  Button as VanButton,
  Icon as VanIcon,
  Popup as VanPopup,
} from 'vant'
import { onMounted, onUnmounted, ref } from 'vue'

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  payment: {
    type: String,
    required: true,
  },
  collection: {
    type: [String, Number],
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
  formData: {
    type: Object,
    required: true,
  },
  user: {
    type: Object,
    default: () => {},
  },
})

const emit = defineEmits(['update:show', 'paymentSuccess', 'paymentCancel'])

// 状态变量
const isTimeout = ref(false)
const queryState = ref(false)
const showCode = ref(props.show)
const order = ref({ tradeNo: '', url: '' })
const timer = ref(null)
const qrcodeTimer = ref(null)
const codeAddress = ref('')
const businessStore = props.user
const userInfo = ref({ ...businessStore })
// 当前登录用户
const currUser = useUserStore().getLogin().f
console.log(userInfo, currUser)

// 创建订单并生成二维码
async function createOrder(): Promise<void> {
  try {
    // 创建订单
    const orderData = {
      config: userInfo.value.f_orgid === '1767' ? 'xianyangkonggang' : 'xianyang',
      pay_way: props.payment.includes('微信') ? 'weixin' : 'ali',
      money: (Number(props.collection) * 100).toFixed(0),
      attach: {
        f_userfiles_id: userInfo.value.f_userfiles_id,
        f_userinfo_code: userInfo.value.f_userinfo_code,
        f_userinfo_id: userInfo.value.f_userinfo_id,
        f_terminal_num: '',
        type: props.type,
        orgId: currUser.resources.orgid,
        orgName: currUser.resources.orgs,
        depId: currUser.resources.depids,
        depName: currUser.resources.deps,
        operator: currUser.resources.name,
        operatorId: currUser.resources.id,
        f_pregas: 0,
        f_preamount: 0,
        f_totalcost: 0,
        f_collection: 0,
        f_add_gas: '',
        payment: props.payment,
        f_outlets: '手持设备',
      },
    }
    if (props.type !== '其他收费' && props.type !== '换表' && props.type !== '补卡') {
      if (props.type === '超用收费') {
        orderData.attach.f_add_gas = props.formData.isAccumulative === true ? '计入' : '不计入'
        orderData.attach.f_pregas = props.formData.overusedGas
        orderData.attach.f_preamount = props.formData.overusedAmount
        orderData.attach.f_totalcost = props.formData.receivedAmount
        orderData.attach.f_collection = props.formData.receivedAmount
      }
      else {
        orderData.attach.f_pregas = props.formData.gas
        orderData.attach.f_preamount = props.formData.money
        orderData.attach.f_totalcost = props.formData.totalCost ? props.formData.totalCost : 0
        orderData.attach.f_collection = props.formData.collection
      }
    }
    else {
      orderData.attach.f_preamount = Number(props.collection)
    }

    const response = await post('/rs/logic/WeiXinGetCode', { data: orderData })
    console.log('生成订单返回结果', response)
    if (response.code === 200) {
      order.value.tradeNo = response.f_out_trade_no
      order.value.url = response.url
      const url = response.url.replace(/&/g, '|')
      codeAddress.value = `/rs/pay/paintCode?url=${url}`
      console.log(codeAddress.value)
      // 显示二维码
      isTimeout.value = true
      // 开始轮询订单状态
      await startOrderStatusPolling(response.f_out_trade_no)
    }
    else {
      showToast('创建订单失败！')
      emit('paymentCancel')
    }
  }
  catch (error) {
    console.error('创建订单失败', error)
    showToast('创建订单失败，请检查网络！')
    emit('paymentCancel')
  }
}

// 轮询订单状态
async function startOrderStatusPolling(tradeNo): Promise<void> {
  let times = 0

  timer.value = setInterval(async () => {
    times++
    try {
      const orderData = {
        f_out_trade_no: tradeNo,
      }

      const result = await post('/af-revenue/logic/mobile_queryThirdOrderState', orderData)
      console.log('==================>', result)
      if (result.length === 0) {
        clearInterval(timer.value)
        showToast({
          message: '未查询到订单信息，请重新点击支付生成订单信息',
          duration: 5000,
        })
        emit('paymentCancel')
      }
      // 支付成功
      if (result[0].f_bill_state === '1') {
        clearInterval(timer.value)
        clearTimeout(qrcodeTimer.value)
        queryState.value = false
        emit('paymentSuccess', { tradeNo, datetime: new Date().toLocaleString() })
      }
      // 支付成功
      if (result[0].f_bill_state === '0') {
        queryState.value = true
      }

      // 支付失败
      if (result[0].f_bill_state === '2') {
        clearInterval(timer.value)
        showToast({
          message: '支付失败或支付超时，请重新点击支付生成二维码',
          duration: 5000,
        })
        emit('paymentCancel')
      }

      // 查询超时
      if (times > 24) {
        clearInterval(timer.value)
        showToast({
          message: '经多次查询用户支付未成功，请重新点击支付生成二维码',
          duration: 5000,
        })
        emit('paymentCancel')
      }
    }
    catch (error) {
      console.error('查询订单状态失败', error)
    }
  }, 5000)
}

// 取消支付
function cancelPayment() {
  showDialog({
    title: '确认取消',
    message: '确定要取消支付吗？',
    showCancelButton: true,
  }).then((action) => {
    if (action === 'confirm') {
      clearTimers()
      emit('update:show', false)
      emit('paymentCancel')
    }
  })
}

// 清除所有定时器
function clearTimers() {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }

  if (qrcodeTimer.value) {
    clearTimeout(qrcodeTimer.value)
    qrcodeTimer.value = null
  }
}

// 组件挂载时创建订单
onMounted(() => {
  if (props.show) {
    createOrder()
  }
})

// 组件卸载时清除定时器
onUnmounted(() => {
  clearTimers()
})
</script>

<template>
  <VanPopup
    v-model:show="showCode"
    :close-on-click-overlay="false"
    :style="{ width: '90%', maxWidth: '400px' }"
  >
    <div class="qrcode-payment">
      <div class="qrcode-payment__header">
        <div class="qrcode-payment__title">
          <VanIcon name="scan" size="24" color="#1989fa" />
          <span>请扫描下方二维码进行付款</span>
        </div>

        <div class="qrcode-payment__amount">
          <span class="qrcode-payment__label">支付金额:</span>
          <span class="qrcode-payment__value">¥{{ props.collection }}元</span>
        </div>
      </div>

      <div class="qrcode-payment__content">
        <div v-if="queryState" class="qrcode-payment__query-tip">
          用户付款过程中，请勿退出或取消！
        </div>
        <div class="qrcode-payment__qrcode-container">
          <img
            v-if="isTimeout"
            :src="codeAddress"
            class="qrcode-payment__timeout-img"
            alt=""
          >
        </div>
      </div>

      <div class="qrcode-payment__footer">
        <VanButton
          type="default"
          block
          @click="cancelPayment"
        >
          取消支付
        </VanButton>
      </div>
    </div>
  </VanPopup>
</template>

<style lang="less" scoped>
.qrcode-payment {
  padding: 20px;

  &__query-tip {
    text-align: center;
    color: #ff4d4f;
    font-size: 14px;
    font-weight: bold;
    background-color: #fff;
    padding: 4px 8px;
    margin-bottom: 12px;
    width: 266px;
    word-wrap: break-word;
    white-space: pre-wrap;
    line-height: 1.4;
  }

  &__header {
    margin-bottom: 20px;
  }

  &__title {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 500;
  }

  &__order-info,
  &__amount {
    display: flex;
    justify-content: center;
    margin-bottom: 8px;
    font-size: 14px;
  }

  &__label {
    color: #646566;
    margin-right: 4px;
  }

  &__value {
    color: #323233;
    font-weight: 500;
  }

  &__content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
  }

  &__qrcode-container {
    position: relative;
    width: 266px;
    height: 266px;
    background-color: #f7f8fa;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &__timeout-img {
    width: 266px;
    height: 266px;
  }

  &__qrcode {
    width: 266px;
    height: 266px;
  }

  &__footer {
    margin-top: 16px;
  }
}
</style>
