<template>
  <view class="container">
    <uv-navbar title="确认订单" placeholder autoBack></uv-navbar>
    <view class="u-text-center u-plr30">
      <view class="mt82">
        <view class="u-ED3D07 u-font44 u-bold">
          ￥
          <text class="u-ml10">{{ total_amount }}</text>
        </view>
        <view class="u-999 u-font22">付款金额</view>
      </view>

      <view class="u-bg-fff pay-select">
        <radio-group @change="e=>payWay(e.detail.value)">
          <!-- <label class="u-flex-center-sb" @click="payWay(0)">
            <view class="u-flex-center">
              <text class="iconfont3 pay">&#x100dc;</text>
              <view class="u-ml20 u-font28 u-181818">
                余额支付<text class="u-font24 u-999"
                  >（可用余额 ¥ {{ balance || 0 }}）</text
                >
              </view>
            </view>
            <view>
              <radio value="0" :checked="payStatus === 0" />
            </view>
          </label> -->
          <label class="u-flex-center-sb u-mt30" @click.stop="payWay(1)">
            <view class="u-flex-center">
              <!-- <image class="img60" src="/static/weChat2.png"></image> -->
              <text class="iconfont pay weixinPay">&#xe663;</text>
              <view class="u-ml20 u-font28 u-181818">微信支付</view>
            </view>
            <view>
              <radio value="1" :checked="payStatus == 1" />
            </view>
          </label>

          <label
            class="u-flex-center-sb u-mt30"
            @click.stop="payWay(2)"
            v-if="env != 0"
          >
            <view class="u-flex-center">
              <text class="iconfont pay zhifuPay">&#xe663;</text>
              <view class="u-ml20 u-font28 u-181818">支付宝</view>
            </view>
            <view>
              <radio value="2" :checked="payStatus == 2" />
            </view>
          </label>
        </radio-group>
      </view>

      <view class="pay-btn">
        <button
          class="u-flex-center u-btn-two"
          @click="$throttle(submitPay, 500)"
        >
          <view class="u-flex-center">
            <view>去付款</view>
            <uni-countdown
              :backgroundColor="'none'"
              :color="'#ffffff'"
              :splitorColor="'#ffffff'"
              :show-day="time1[0] > 0"
              :day="time1[0]"
              :hour="time1[1]"
              :minute="time1[2]"
              :second="time1[3]"
            >
            </uni-countdown>
          </view>
        </button>
        <view class="u-flex-center u-mt20 u-999 u-font22">
          <view> 请在 </view>
          {{ payMinutes }}
          <view>分钟内完成付款，否则订单失效。</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import {
  shoporderInfo_Api,
  shopOrderGoPay_Api,
  shopOrderIsPay_Api,
} from "@/api/order";
import { totalBalance_Api } from "@/api/userInfo.js";
import $mUtil from "@/util/index";
// 响应式数据
const total_amount = ref(null);
const orderNo = ref(null);
const orderId = ref(null);
const loading = ref(false);
const expired_pay_time = ref(null);
const payStatus = ref(1);
const balance = ref(null);
const isGroup = ref(false);
const isService = ref(false);
const time1 = reactive([0, 0, 0, 0]);
const payMinutes = ref(0); // 支付剩余分钟数
const pagesType = ref(null); // 页面类型, 1：通知上个页面支付成功

const eventChannel = ref(null);
onMounted(() => {
  const instance = getCurrentInstance().proxy;
  eventChannel.value = instance.getOpenerEventChannel();
});
const env = ref(2);
let weixinInfo = null;
const orderInfo = ref({});
const getOrderInfo = () => {
  shoporderInfo_Api(orderId.value).then((res) => {
    if (res && res.code == 200) {
      orderInfo.value = res.data || {};
      if (orderInfo.value.paymentMethod != null) {
        payStatus.value = orderInfo.value.paymentMethod;
      }
    }
  });
};

// 页面加载
onLoad((options) => {
  // console.log(options, "options");
  // 微信小程序
  // #ifdef MP-WEIXIN
  env.value = 0;
  payStatus.value = 0;
  // #endif

  if (options.orderNo) {
    orderNo.value = options.orderNo;
  }
  if (options.orderId) {
    orderId.value = options.orderId;
    getOrderInfo();
  }
  if (options.total_amount) {
    total_amount.value = options.total_amount;
  }
  if (options.pagesType) pagesType.value = options.pagesType;
  if (options.expired_pay_time) {
    expired_pay_time.value = options.expired_pay_time;
    const timeArray = $mUtil
      .countDown(expired_pay_time.value)
      .split(":")
      .map((val) => Number(val));
    time1[0] = timeArray[0];
    time1[1] = timeArray[1];
    time1[2] = timeArray[2];
    time1[3] = timeArray[3];
    // console.log("支付时间：" + options.expired_pay_time);
    let beginTime = new Date();
    let time = expired_pay_time.value - beginTime;
    let leave1 = time % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    //计算相差分钟数
    let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    let minutes = Math.ceil(leave2 / (60 * 1000));
    // payMinutes.value = minutes
    // console.log("分钟值:" + minutes);
  }
  if (options.type && options.type == "group") {
    isGroup.value = true;
  }
  if (options.type && options.type == "service") {
    isService.value = true;
  }

  // accountInfo();
  // if (options.orderId) {
  //   returnList(options.orderId);
  // }
  // console.log("分钟" + time1[2]);
  if (time1[3] == "0") {
    payMinutes.value = time1[2];
  } else {
    payMinutes.value = time1[2] + 1;
  }
  // console.log("秒值：" + time1[3]);

  // #ifdef APP-PLUS
  plus.share.getServices(
    (service) => {
      let weixin = service.find((i) => i.id === "weixin");
      if (weixin) {
        // console.log("weixin==>", weixin);
        weixinInfo = weixin;
      } else {
        // 没有获取到微信分享服务
        console.log(weixin);
      }
    },
    (err) => {
      // 获取分享服务列表失败
      console.log(err);
    }
  );
  // #endif
});

const showPaying = ref(false); // 是否支付中
// 订单支付状态查询
const shopOrderIsPay = () => {
  shopOrderIsPay_Api({ orderId: orderId.value })
    .then((res) => {
      uni.hideLoading();
      if (res && res.code == 200) {
        let title = "支付成功";
        if (!res.data) {
          title = "支付失败";
        }
        uni.showToast({ title, icon: "none" });
      }
      goJump();
    })
    .catch((err) => {
      goJump();
    });
};

// 页面显示
onShow(() => {
  if (showPaying.value) {
    uni.showLoading({ title: "加载中...", mask: true });
    setTimeout(() => {
      shopOrderIsPay();
    }, 500);
  }
});

// // 获取账户信息
// const accountInfo = () => {
//   totalBalance_Api().then((res) => {
//     if (res && res.code == 200) {
//       balance.value = res.data || 0;
//     }
//   });
// };

// 选择支付方式
const payWay = (e) => {
  // console.log(e, 111);
  payStatus.value = e;
};

// 跳转页面
const goJump = () => {
  if (pagesType.value == 1 || pagesType.value == 2) {
    setTimeout(() => {
      eventChannel.value.emit("callback");
      uni.navigateBack();
    }, 500);
  } else {
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/order/mallOrder/orderList?orderType=0`,
      });
    }, 500);
  }
};

// 确认支付
const confirm = () => {
  if (env.value == 0) {
    uni.navigateToMiniProgram({
      appId: "wxcea8ce8b537d83a5",
      path: `pages/order/detail?orderId=${orderId.value}&type=0`,
      envVersion: "release", // develop（开发版），trial（体验版），release（正式版）
      success: (res) => {
        showPaying.value = true;
      },
      fail: (res) => {
        console.log("取消支付：" + res);
      },
    });
  } else {
    showPaying.value = true;
    let isAndroid = true;
    // #ifdef APP-PLUS
    if (plus.os.name == "Android") {
      console.log("当前环境是安卓");
      isAndroid = true;
    } else {
      console.log("当前环境不是安卓");
      isAndroid = false;
    }
    // 微信支付
    if (payStatus.value == 0) {
      // console.log("微信支付===================");
      // #ifdef APP-PLUS
      weixinInfo.launchMiniProgram(
        {
          id: "gh_e5657eb120b6",
          path: `/pages/order/detail?orderId=${orderId.value}`,
          type: "0",  // 可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
          // webUrl
        },
        (res) => {
          console.log("res", res);
        },
        (err) => {
          console.log("err", err);
        }
      );
      // #endif
    } else {
      // console.log("支付宝支付===================");
      // 支付宝支付
      //参数需要
      const query = encodeURIComponent("?orderId=" + orderId.value);
      const url = `${
        isAndroid ? "alipays" : "alipay"
      }://platformapi/startapp?appId=2021006116626014&page=pages/order/detail${query}`;
      plus.runtime.openURL(url, (e) => {
        console.error("未安装支付宝或无法打开");
        showPaying.value = false;
        uni.$uv.toast("未安装支付宝或无法打开");
      });
    }
    // #endif
  }
};

// 提交支付
const submitPay = () => {
  if (!orderId.value) {
    uni.$uv.toast("未获取到订单号");
    return;
  }

  if (payStatus.value != orderInfo.value.paymentMethod) {
    uni.showLoading({ title: "支付中...", mask:true });
    shopOrderGoPay_Api({ orderId: orderId.value, paymentMethod: payStatus.value }).then(res => {
      uni.hideLoading();
      if (res && res.code == 200) {
        confirm();
      }
    })
  } else {
    confirm();
  }
  
};

// // 提交支付
// const submitPay = () => {
//   //微信支付
//   if (
//     payStatus.value == 1 ||
//     payStatus.value == 2 ||
//     payStatus.value == 10 ||
//     payStatus.value == 12 ||
//     payStatus.value == 14
//   ) {
//     let data = {
//       orderNo: orderNo.value,
//     };
//     loading.value = true;
//     shoporderWxMinPay_Api(data)
//       .then((res) => {
//         if (res && res.data.code == 200) {
//           loading.value = false;
//           let target = res.data.data;
//           console.log("target==>>", target);
//           if (payStatus.value == 1) {
//             uni.requestPayment({
//               provider: "wxpay",
//               timeStamp: target.timeStamp,
//               nonceStr: target.nonceStr,
//               package: target.package,
//               signType: target.signType,
//               paySign: target.paySign,
//               success: (res) => {
//                 uni.$uv.toast("支付成功");
//                 uni.removeStorageSync("orderreminder");
//                 goJump();
//               },
//               fail: function (err) {
//                 console.log("err==>", err);
//                 loading.value = false;
//                 console.log("fail:" + JSON.stringify(err));
//               },
//             });
//           } else if (payStatus.value == 2) {
//             uni.requestPayment({
//               provider: "alipay",
//               orderInfo: target.prePayOrderInfo,

//               success: (res) => {
//                 uni.$uv.toast("支付成功");
//                 uni.removeStorageSync("orderreminder");
//                 goJump();
//               },
//               fail: function (err) {
//                 loading.value = false;
//                 console.log("fail:" + JSON.stringify(err));
//               },
//             });
//           }
//         } else {
//           loading.value = false;
//           uni.$uv.toast("交易失败");
//         }
//       })
//       .catch((err) => {
//         loading.value = false;
//         // getApp().globalData.$mUtil.toast('交易失败');
//       });
//   } else if (payStatus.value == 0) {
//     //余额支付
//     loading.value = false;
//     uni.showModal({
//       title: "余额支付",
//       content: "确定使用余额支付吗？",
//       success: (res) => {
//         if (res.confirm) {
//           let data = {
//             orderNo: orderNo.value,
//           };
//           shoporderBalance_Api(data).then((res) => {
//             if (res && res.code == 200) {
//               uni.removeStorageSync("orderreminder");
//               uni.$uv.toast("支付成功");
//               goJump();
//             }
//           });
//         } else if (res.cancel) {
//         }
//       },
//     });
//   }
// };
</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
}

.mt82 {
  margin-top: 82rpx;
}

radio {
  transform: scale(0.7);
}

.pay-select {
  margin-top: 66rpx;
  border-radius: 18rpx;
  padding: 48rpx 38rpx;

  .pay {
    font-size: 60rpx;
    // color: #ffa937;
  }

  .weixinPay {
    color: #09bb07;
  }

  .zhifuPay {
    color: #06b4fd;
  }
  .banks {
    justify-content: center;
  }

  .bank {
    display: flex;
    // flex-direction: column;
    justify-content: space-between;
    align-items: center;

    .box {
      // display: flex;
      // justify-content: space-between;
      // align-items: center;

      &:first-child {
        margin-bottom: 10rpx;
      }

      .left {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;
      }

      image {
        width: 80rpx;
        height: auto;
        margin-right: 10rpx;
      }

      .bank_name {
        font-size: 28rpx;
        margin-right: 20rpx;
        // font-weight: bold;
      }

      .name {
        text-align: left;
      }
    }
  }

  .bank-box {
    flex: 1;
    width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .bank-icon {
    color: #2f77f1;
    font-size: 60rpx;
  }
}

.img60 {
  width: 50rpx;
  height: 50rpx;
  margin-left: 6rpx;
}

.pay-btn {
  margin-top: 80rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  align-content: center;

  button {
    background-color: #fa6138;
    color: #ffffff;
    justify-content: center;
  }
}
</style>
