<template>
  <up-popup :show="showPopup" :closeOnClickOverlay="true" @close="close">
    <view class="payment">
      <view class="title acea-row row-center-wrapper">
        选择付款方式<text class="iconfont icon-guanbi" @click="close"></text>
      </view>
      <view
        class="item acea-row row-between-wrapper"
        @click="goPay(item)"
        v-for="(item, index) in payMode"
        :key="index"
      >
        <view class="left acea-row row-between-wrapper">
          <view class="iconfont" :class="item.icon"></view>
          <view class="text">
            <view class="name">{{ item.name }}</view>
            <view class="info" v-if="item.value === 'yue'">
              {{ item.title }}
              <span class="money">￥{{ appStore.userInfo.nowMoney }}</span>
            </view>
            <view class="info" v-else>{{ item.title }}</view>
          </view>
        </view>
        <!-- <view class="iconfont icon-xiangyou"></view> -->
      </view>
    </view>
  </up-popup>
</template>

<script setup>
import { computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { usePayment } from "@/hooks/usePayment.js";
import { wechatOrderPay, wechatQueryPayResult } from "@/api/order.js";
import { useAppStore } from "@/stores/app";
import { useToast } from "@/hooks/useToast";
import { getUserInfo } from "@/api/user";

const emit = defineEmits(["closePopup", "payComplete", "payFail"]);

const { Toast } = useToast();
const { submitPayment } = usePayment();

const props = defineProps({
  mallType: {
    type: Number,
    default: 0, // 0: 水贝商城 1: 贝币商城
  },
  payMode: {
    type: Array,
    default: () => [],
  },
  showPopup: {
    type: Boolean,
    default: false,
  },
  order_id: {
    type: String,
    default: "",
  },
  totalPrice: {
    type: String,
    default: "0",
  },
});

const appStore = useAppStore();
const systemPlatform = computed(() => appStore.systemPlatform);

function close() {
  // emit("onChangeFun", { action: "payClose" });
  emit("closePopup");
}

async function fetchUserInfo() {
  const { data } = await getUserInfo();
  appStore.UPDATE_USERINFO(data);
}

onLoad(() => {
  fetchUserInfo();
});

async function goPay(item) {
  try {
    const number = item.number || 0;
    const paytype = item.value;
    let goPages = "/pages/order_pay_status/index?order_id=" + props.order_id;
    if (!props.order_id) {
      return Toast({ title: "请选择要支付的订单" });
    }
    if (
      paytype === "yue" &&
      parseFloat(number) < parseFloat(props.totalPrice)
    ) {
      return Toast({ title: "余额不足！" });
    }
    uni.showLoading({ title: "支付中" });
    const params = {
      mallType: props.mallType,
      orderNo: props.order_id,
      payChannel: item.payChannel,
      payType: paytype,
    };
    const res = await wechatOrderPay(params);
    let jsConfig = res.data.jsConfig;
    let orderId = res.data.orderNo;
    switch (res.data.payType) {
      case "alipay":
        const result = await submitPayment({
          type: res.data.payType,
          orderInfo: res.data.alipayRequest,
        });
        if (result && result.status === "success") {
          emit("payComplete");
          return Toast(
            { title: result.message, icon: "success" },
            { tab: 4, url: goPages }
          );
        } else {
          emit("payFail", { message: result.message || "支付失败" });
          return Toast(
            { title: result.message },
            { tab: 5, url: goPages + "&status=0" }
          );
        }
        break;
      case "yue":
        Toast(
          { title: "余额支付成功", icon: "success" },
          { tab: 4, url: goPages }
        );
        emit("payComplete");
        break;
      case "weixinh5":
        location.replace(
          jsConfig.mwebUrl +
            "&redirect_url=" +
            window.location.protocol +
            "//" +
            window.location.host +
            goPages +
            "&status=1"
        );
        Toast({ title: "支付中" });
        emit("payComplete");
        break;
      case "weixinApp":
        const wxPayResult = await submitPayment({
          type: res.data.payType,
          orderInfo: res.data.prepayWithRequestPaymentResponse,
        });
        let wxPayFailMsg = wxPayResult?.message || "支付失败";
        if (wxPayResult.status === "支付成功") {
          emit("payComplete");
          return Toast(
            { title: "支付成功", icon: "success" },
            { tab: 4, url: goPages }
          );
        } else if (wxPayResult.status === "支付失败") {
          emit("payFail", { message: wxPayFailMsg });
          return Toast(
            { title: "支付失败" },
            { tab: 5, url: `${goPages}&msg=${wxPayFailMsg}` }
          );
        } else if (wxPayResult.status === "用户取消支付") {
          emit("payFail", { message: "用户取消支付" });
          return Toast(
            { title: "用户取消支付" },
            {
              tab: 5,
              url: `${goPages}&msg=用户取消支付`,
            }
          );
        }
        break;
    }
  } catch (error) {
    console.error("goPay error", error);
    emit("payFail", { message: error.message || error.msg || "支付失败" });
    return Toast({
      title: error.message || error.msg || "支付失败",
    });
  } finally {
    uni.hideLoading();
  }
}
</script>

<style scoped lang="scss">
.payment {
  background-color: #fff;
}

.payment .title {
  text-align: center;
  height: 123rpx;
  font-size: 32rpx;
  color: #282828;
  font-weight: bold;
  padding-right: 30rpx;
  margin-left: 30rpx;
  position: relative;
  border-bottom: 1rpx solid #eee;
}

.payment .title .iconfont {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 43rpx;
  color: #8a8a8a;
  font-weight: normal;
}

.payment .item {
  border-bottom: 1rpx solid #eee;
  height: 130rpx;
  margin-left: 30rpx;
  padding-right: 30rpx;
}

.payment .item .left {
  width: 610rpx;
}

.payment .item .left .text {
  width: 540rpx;
}

.payment .item .left .text .name {
  font-size: 32rpx;
  color: #282828;
}

.payment .item .left .text .info {
  font-size: 24rpx;
  color: #999;
}

.payment .item .left .text .info .money {
  color: #ff9900;
}

.payment .item .left .iconfont {
  font-size: 45rpx;
  color: #09bb07;
}

.payment .item .left .iconfont.icon-zhifubao {
  color: #00aaea;
}

.payment .item .left .iconfont.icon-balance {
  color: #ff9900;
  font-size: 50rpx;
}

.payment .item .left .iconfont.icon-yuezhifu1 {
  color: #eb6623;
}

.payment .item .iconfont {
  font-size: 0.3rpx;
  color: #999;
}
</style>
