<script setup>
import { ref, onMounted } from "vue";
import Container from "@/components/Container.vue";
import SButton from "@/components/SButton.vue";
import { payOrderAPI, cancelOrderListAPI, getHomeData } from "@/apis";
import { orderStatusNames } from "@/constants";
import useStore from "@/store";
const store = useStore();
const { updateUser } = store;

const data = ref({});
const loading = ref(false);

onMounted(() => {
  const order = uni.getStorageSync("order");
  data.value = order || {};
});

const goPay = async () => {
  const result = await payOrderAPI(data.value.orderId);
  const params = result.jsApi.params;
  if (params) {
    loading.value = true;
    wx.requestPayment({
      timeStamp: params.timeStamp, // 时间戳
      nonceStr: params.nonceStr, // 随机字符串
      package: params.package, // 统一下单接口返回的 prepay_id 参数值，格式：prepay_id=***
      paySign: params.paySign, // 签名
      signType: "RSA", // 签名类型，默认为RSA
      async success(res) {
        const result = await getHomeData();
        if (result.user) updateUser(result.user);
        uni.showToast({
          title: "支付成功",
          icon: "none",
        });
      },
      fail(res) {
        loading.value = false;
        console.log("pay error", res);
      },
    });
  }
};

const cancelOrder = async () => {
  const result = await cancelOrderListAPI(data.value.orderId);
  data.value = result;
};
</script>

<template>
  <Container title="订单详情">
    <view class="container">
      <view class="order">
        <view>
          <text>商品名：{{ data.vipName }}</text>
          <text>订单号：{{ data.orderId }}</text>
          <text>下单时间：{{ data.vipCreateAt }}</text>
          <text
            >支付时间：{{
              data.orderStatus === 4 ? data.paymentTime : ""
            }}</text
          >
          <text>金额：{{ data.total }} 元</text>
          <text>支付方式：微信</text>
        </view>
        <view v-if="data.orderStatus === 1">
          <SButton :onClick="goPay">去支付</SButton>
          <view :style="{ height: '10px' }" />
          <SButton :onClick="cancelOrder">取消订单</SButton>
        </view>
      </view>
    </view>
  </Container>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  padding-top: 10px;
}
.order {
  width: 100%;
  height: 100%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.order > view:first-child {
  display: flex;
  flex-direction: column;
  padding: 15px;
}
.order > view:first-child > text:first-child {
  color: #000;
  font-size: 16px;
}
.order > view:first-child > text {
  color: #666666;
  font-size: 13px;
  margin-top: 5px;
}
.order > view:last-child {
  margin-bottom: 20px;
}
</style>
