<template>
  <Container
    title="挑战"
    :scrollStyle="{
      padding: 0,
    }"
    :showBack="false"
  >
    <view>
      <view class="bg"></view>
    </view>
    <template #stick>
      <button class="btn" @click="toAdd">立即报名！参与挑战！</button>
    </template>
  </Container>
</template>

<script setup>
import Container from "../../components/Container/Container.vue";
import { request } from "../../utils/request";
import { router } from "../../utils/router";
import { onShow } from "@dcloudio/uni-app";
import { ref, getCurrentInstance } from "vue";
import ext from "../../ext.json";
const instance = getCurrentInstance();
const isPay = ref(true);

const p = ref(0);
onShow(async () => {
  const res = request(
    "api/question_bank/question_reception/challenge_registration_log/detail"
  );
  if (res.data) return;
  isPay.value = false;
  request(
    "api/question_bank/question_reception/recharge_package/list",
    {
      package_type: 2,
    },
    "post"
  ).then(async (res) => {
    p.value = res.data.data[0].id;
  });
});

const toAdd = async () => {
  if (isPay.value) {
    router.push({
      url: "/pages/challenge/addContant",
    });
    return;
  }
  uni.login({
    provider: instance.proxy.$mpPlatform.substring(3),
    success: async ({ code }) => {
      const package_id = p.value;
      // 先调用新增订单再支付
      const order = await request(
        "api/question_bank/question_reception/orders/add",
        {
          package_id,
        }
      );
      const e = await request(
        "api/question_bank/question_reception/orders/wechat_pay",
        {
          code,
          order_id: order.data.order_id,
          app_id: ext.extAppid,
        }
      );

      uni.requestPayment({
        provider: "wxpay",
        timeStamp: e.data.timeStamp, //时间戳
        nonceStr: e.data.nonceStr, //随机字符串
        package: e.data.package, //prepay_id
        signType: e.data.signType, //签名算法MD5
        paySign: e.data.paySign, //签名,
        success(res) {
          console.log(res);
          router.push({
            url: "/pages/challenge/addContant",
          });
        },
        fail(err) {
          console.log(err);
        },
      });
    },
  });
};
</script>

<style lang="scss" scoped>
.bg {
  width: 100%;
  height: 1734rpx;
  background: url("https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/05/IFolqhKEbaTWdBgII6gjvqMKrf8WUbbgEpoeRH5t.png");
  background-size: cover;
  padding: 32rpx;
  box-sizing: border-box;
}

.btn {
  width: 660rpx;
  position: absolute;
  bottom: 3%;
  left: 50%;
  transform: translateX(-50%);
}
</style>
