<template>
  <up-popup :show="showPopup" :closeOnClickOverlay="true" @close="close">
    <view class="payment">
      <view class="title acea-row row-center-wrapper">
        <view class="lable">选择付款方式</view>
        <view class="value"
          >实付金额:<text class="price">{{ orderUserInfo.totalCount }}</text
          >元</view
        >
      </view>

      <view class="materials">
        <view class="iconfont-box">
          <view class="iconfont icon-balance"></view>
          <view class="text">
            <view class="name">余料支付</view>
            <view class="info" v-if="goldType === 'au'">
              黄金余料:
              <span class="money">￥{{ orderUserInfo.auBalance || 0 }}g</span>
            </view>
            <view class="info" v-if="goldType === 'ag'">
              白银余料:
              <span class="money">￥{{ orderUserInfo.agBalance || 0 }}g</span>
            </view>
            <view class="info" v-if="goldType === 'pt'">
              铂金余料:
              <span class="money">￥{{ orderUserInfo.ptBalance || 0 }}g</span>
            </view>
          </view>
        </view>
        <!-- <up-switch
          activeColor="#eb6623"
          v-model="materials"
          @change="handleChange"
        ></up-switch> -->
      </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">￥{{ orderUserInfo.nowMoney }}</span>
            </view>
            <view class="info" v-else>{{ item.title }}</view>
          </view>
        </view>
      </view>
    </view>
  </up-popup>
</template>

<script setup>
import { ref } from "vue";
import { svipBuy } from "@/api/svip";
import { BalanceMoneyAPI } from "@/api/find_fund.js";
import { alipayPaymentResult } from "@/api/order.js";
import { useAppStore } from "@/stores/app";
import { useToast } from "@/hooks/useToast";
import { usePayment } from "@/hooks/usePayment.js";
import { getUserInfo } from "@/api/user";

// 余料支付开关状态
const materials = ref(false);

// 定义可从外部触发的事件
const emit = defineEmits(["closePopup", "payComplete", "payFail", "change"]);

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

const props = defineProps({
  payMode: {
    type: Array,
    default: () => [],
  },
  showPopup: {
    type: Boolean,
    default: false,
  },
  totalPrice: {
    type: String,
    default: "0",
  },
  goldType: {
    type: String,
    default: "au",
  },
  orderId: {
    type: Number,
    default: 0,
  },
  orderUserInfo: {
    type: Object,
    default: () => ({}),
  },
  addresssId: {
    type: Number,
    default: 0,
  },
  switchStatus: {
    type: Boolean,
    default: false,
  },
});

const appStore = useAppStore();
// 关闭弹窗
function close() {
  emit("closePopup");
}

// 处理开关变化，同时触发外部事件
const handleChange = (e) => {
  emit("change", e);
};

// 暴露给父组件的方法，用于外部触发change事件
const triggerChange = (value) => {
  materials.value = value;
  // handleChange(value);
};

// 暴露方法给父组件
defineExpose({
  triggerChange,
});

// 处理支付
async function goPay(item) {
  console.log("goPay", item);
  try {
    const paytype = item.value;
    if (
      paytype === "yue" &&
      parseFloat(props.orderUserInfo.nowMoney) <
        parseFloat(props.orderUserInfo.totalCount)
    ) {
      return Toast({ title: "余额不足！" });
    }
    uni.showLoading({ title: "支付中" });

    switch (paytype) {
      case "alipay":
        await handleAlipayPayment(paytype);

        break;
      case "weixin":
        handleWechatPayment();
        break;
      case "yue":
        const res = await BalanceMoneyAPI(
          props.orderId,
          props.addresssId,
          true
        );
        console.log("res==>", res);
        // 充值成功后获取用户信息更新余额
        const { data } = await getUserInfo();
        appStore.UPDATE_USERINFO(data);
        uni.hideLoading();
        Toast({ title: "余额支付成功" });
        emit("payComplete");
        break;
      case "weixinh5":
        uni.hideLoading();
        // 注意：这里的jsConfig和goPages需要在实际环境中定义
        location.replace(
          jsConfig.mwebUrl +
            "&redirect_url=" +
            window.location.protocol +
            "//" +
            window.location.host +
            goPages +
            "&status=1"
        );
        Toast({ title: "支付中" });
        emit("payComplete");
        break;
    }
  } catch (error) {
    console.error("goPay error", error);
    uni.hideLoading();
    return Toast({
      title: error.message || "支付失败,余料不足，请充值！",
    });
  }
}

// 支付宝支付处理
async function handleAlipayPayment(payType) {
  try {
    const res = await svipBuy({
      payType,
      price: props.totalPrice,
      userId: appStore.$userInfo.userId,
    });
    const result = await submitPayment({
      type: "alipay",
      orderInfo: res.data.alipayRequest,
    });
    console.log("handleAlipayPayment", result, res);

    if (result.status === paymentConfig.PAYMENT_STATUS.SUCCESS) {
      const params = {
        orderNo: res.data.orderNo,
        payType: "alipay",
      };
      // 查询后端支付状态接口
      await alipayPaymentResult(params);

      // 充值成功后获取用户信息更新余额
      const { data } = await getUserInfo();
      appStore.UPDATE_USERINFO(data);

      Toast({
        title: "支付成功",
        icon: "success",
      });
      emit("payComplete");
    } else if (result.status === paymentConfig.PAYMENT_STATUS.FAIL) {
      Toast({ title: "支付失败" });
      emit("payFail");
    } else if (result.status === paymentConfig.PAYMENT_STATUS.CANCEL) {
      Toast({ title: "已取消支付" });
    }
  } catch (error) {
    let msg = "支付失败，请稍后再试";
    if (typeof error === "string") {
      msg = error;
    } else if (typeof error === "object" && error.message) {
      msg = error.message;
    }
    Toast({ title: msg });
    emit("payFail");
    console.error("handleAlipayPayment", error);
  } finally {
    uni.hideLoading();
  }
}

// 微信支付处理
const handleWechatPayment = () => {
  Toast({
    title: `准备使用微信充值 ¥${props.totalPrice}`,
    icon: "none",
  });
  // 这里调用微信支付相关接口
  // 例如：uni.requestPayment({ provider: 'wxpay', ... })
};
</script>

<style scoped lang="scss">
.materials .iconfont.icon-balance {
  color: #eb6623;
  font-size: 50rpx;
}
.materials {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  height: 130rpx;
  border-bottom: 1rpx solid #eee;

  .iconfont-box {
    display: flex;
    align-items: center;
    .text {
      margin-left: 18rpx;
      .name {
        font-size: 32rpx;
        color: #282828;
      }
      .info {
        font-size: 24rpx;
        color: #999;
        .money {
          color: #ff9900;
        }
      }
    }
  }
}
.payment {
  background-color: #fff;
}

.payment .title {
  height: 123rpx;
  font-size: 32rpx;
  color: #282828;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
  .value {
    .price {
      margin: 0 8rpx;
      color: #eb6623;
    }
  }
}

.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>
