<template>
  <view class="container">
    <view class="content"></view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { common } from '@/utils';
import { orderDetailLocal } from '@/pagesPatient/service/record/index';

const orderId = ref('');
// const timesMax = ref(5); // 原逻辑中定义了但未使用，或者仅作为常量
let times = 0;
let timer: any = null;

const sleep = (val: string | number) => {
  let times = Number(val);
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true);
    }, times);
  });
};

const main = async () => {
  /** 500毫秒后再执行其他操作 否则loading直接被hide 不显示遮罩 */
  await sleep(500);

  const mainInner = async () => {
    times++;
    /** 轮询5次 */
    if (times > 5) {
      uni.hideLoading();
      common.showModal(`当前订单等待超时,请前往订单记录页面核实订单结果,谢谢您的配合,祝您早日康复。`, () => {
        common.goToUrl('/pages/st1/business/tabbar/homePage/homePage', {
          skipWay: "reLaunch"
        });
      });
      return;
    }

    if (orderId.value) {
      const queryData = {
        OrderId: orderId.value
      };

      try {
        let { resp } = await orderDetailLocal(queryData, false);
        if (common.isNotEmpty(resp)) {
          // 兼容原逻辑，假设 resp 为数组
          const order = Array.isArray(resp) ? resp[0] : resp;
          
          if (order && order.BizState == '1') {
            /** 支付成功 */
            uni.hideLoading();
            common.goToUrl(`/pagesPatient/st1/business/pay/payState/payState?orderId=${order.OrderId}`, {
              skipWay: "redirectTo"
            });
            return;
          } else if (order && order.BizState == '2') {
            /** 支付失败 */
            uni.hideLoading();
            common.showModal(`订单支付失败`, () => {
              common.goToUrl('/pages/st1/business/tabbar/homePage/homePage', {
                skipWay: "reLaunch"
              });
            });
            return;
          }
        }
      } catch (e) {
        console.error(e);
      }

      timer = setTimeout(() => {
        mainInner();
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
      }, 2000);
    }
  };

  mainInner();
};

onLoad((options: any) => {
  uni.showLoading({
    title: '支付中',
    mask: true
  });
  orderId.value = options.orderId || "";
  main();
});
</script>

<style lang="scss">
.container {
}
</style>
